Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make data limits a permanent feature #698

Merged
merged 15 commits into from
Jul 20, 2020
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/server_manager/messages/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
"confirmation-server-remove": "This action removes your server from the Outline Manager, but does not block proxy access to users. You will still need to manually delete the Outline server from your host machine.",
"confirmation-server-remove-title": "Remove Server?",
"data-limits": "Data limits",
"data-limits-description": "Set a 30 day trailing data transfer limit for access keys on this server. Available at least until {date}.",
"data-limits-description": "Set a 30 day trailing data transfer limit for access keys on this server.",
"data-limits-dialog-text": "Go to the Settings tab to set a data transfer limit for access keys on this server.",
"data-limits-dialog-title": "Avoid data overages",
"data-limits-usage": "{used} of {total} used",
Expand Down
10 changes: 2 additions & 8 deletions src/server_manager/messages/master_messages.json
Original file line number Diff line number Diff line change
Expand Up @@ -126,14 +126,8 @@
"description": "This string appears as a title in a section to configure access key data transfer limits."
},
"data_limits_description": {
"message": "Set a 30 day trailing data transfer limit for access keys on this server. Available at least until $DATE$.",
"description": "This string appears as an explanation to the access key data transfer limits feature.",
"placeholders": {
"DATE": {
"content": "{date}",
"example": "December 9, 2019"
}
}
"message": "Set a 30 day trailing data transfer limit for access keys on this server.",
"description": "This string appears as an explanation to the access key data transfer limits feature."
},
"data_limits_dialog_text": {
"message": "Go to the Settings tab to set a data transfer limit for access keys on this server.",
Expand Down
2 changes: 1 addition & 1 deletion src/server_manager/web_app/app.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -247,7 +247,7 @@ function createTestApp(
return new App(
polymerAppRoot, VERSION, fakeDigitalOceanSessionFactory,
fakeDigitalOceanServerRepositoryFactory, manualServerRepo, displayServerRepository,
digitalOceanTokenManager, new FakeSurveys());
digitalOceanTokenManager);
}

enum AppRootScreen {
Expand Down
9 changes: 1 addition & 8 deletions src/server_manager/web_app/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ import * as digitalocean_api from '../cloud/digitalocean_api';
import * as errors from '../infrastructure/errors';
import {sleep} from '../infrastructure/sleep';
import * as server from '../model/server';
import {Surveys} from '../model/survey';

import {TokenManager} from './digitalocean_oauth';
import * as digitalocean_server from './digitalocean_server';
Expand All @@ -37,8 +36,6 @@ const UNUSED_DIGITALOCEAN_REFERRAL_CODE = '5ddb4219b716';
const CHANGE_KEYS_PORT_VERSION = '1.0.0';
const DATA_LIMITS_VERSION = '1.1.0';
const CHANGE_HOSTNAME_VERSION = '1.2.0';
// Date by which the data limits feature experiment will be permanently added or removed.
export const DATA_LIMITS_AVAILABILITY_DATE = new Date('2020-06-02');
const MAX_ACCESS_KEY_DATA_LIMIT_BYTES = 50 * (10 ** 9); // 50GB

function dataLimitToDisplayDataAmount(limit: server.DataLimit): DisplayDataAmount|null {
Expand Down Expand Up @@ -131,7 +128,7 @@ export class App {
private createDigitalOceanServerRepository: DigitalOceanServerRepositoryFactory,
private manualServerRepository: server.ManualServerRepository,
private displayServerRepository: DisplayServerRepository,
private digitalOceanTokenManager: TokenManager, private surveys: Surveys) {
private digitalOceanTokenManager: TokenManager) {
appRoot.setAttribute('outline-version', this.version);

appRoot.addEventListener('ConnectToDigitalOcean', (event: CustomEvent) => {
Expand Down Expand Up @@ -834,8 +831,6 @@ export class App {
view.serverPortForNewAccessKeys = selectedServer.getPortForNewAccessKeys();
view.serverCreationDate = localizeDate(selectedServer.getCreatedDate(), this.appRoot.language);
view.serverVersion = selectedServer.getVersion();
view.dataLimitsAvailabilityDate =
localizeDate(DATA_LIMITS_AVAILABILITY_DATE, this.appRoot.language);
view.accessKeyDataLimit = dataLimitToDisplayDataAmount(selectedServer.getAccessKeyDataLimit());
view.isAccessKeyDataLimitEnabled = !!view.accessKeyDataLimit;

Expand Down Expand Up @@ -1025,7 +1020,6 @@ export class App {
this.appRoot.showNotification(this.appRoot.localize('saved'));
serverView.accessKeyDataLimit = dataLimitToDisplayDataAmount(limit);
this.refreshTransferStats(this.selectedServer, serverView);
this.surveys.presentDataLimitsEnabledSurvey();
} catch (error) {
console.error(`Failed to set access key data limit: ${error}`);
this.appRoot.showError(this.appRoot.localize('error-set-data-limit'));
Expand All @@ -1041,7 +1035,6 @@ export class App {
await this.selectedServer.removeAccessKeyDataLimit();
this.appRoot.showNotification(this.appRoot.localize('saved'));
this.refreshTransferStats(this.selectedServer, serverView);
this.surveys.presentDataLimitsDisabledSurvey();
} catch (error) {
console.error(`Failed to remove access key data limit: ${error}`);
this.appRoot.showError(this.appRoot.localize('error-remove-data-limit'));
Expand Down
8 changes: 2 additions & 6 deletions src/server_manager/web_app/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,11 @@ import * as digitalocean_api from '../cloud/digitalocean_api';
import * as i18n from '../infrastructure/i18n';
import {getSentryApiUrl} from '../infrastructure/sentry';

import {App, DATA_LIMITS_AVAILABILITY_DATE} from './app';
import {App} from './app';
import {DigitalOceanTokenManager} from './digitalocean_oauth';
import * as digitalocean_server from './digitalocean_server';
import {DisplayServerRepository} from './display_server';
import {ManualServerRepository} from './manual_server';
import {DEFAULT_PROMPT_IMPRESSION_DELAY_MS, OutlineSurveys} from './survey';
import {AppRoot} from './ui_components/app-root.js';

const SUPPORTED_LANGUAGES: {[key: string]: {id: string, dir: string}} = {
Expand Down Expand Up @@ -107,10 +106,7 @@ document.addEventListener('WebComponentsReady', () => {
new App(
appRoot, version, digitalocean_api.createDigitalOceanSession,
digitalOceanServerRepositoryFactory, new ManualServerRepository('manualServers'),
new DisplayServerRepository(), new DigitalOceanTokenManager(),
new OutlineSurveys(
appRoot.$.surveyDialog, localStorage, DEFAULT_PROMPT_IMPRESSION_DELAY_MS,
DATA_LIMITS_AVAILABILITY_DATE))
new DisplayServerRepository(), new DigitalOceanTokenManager())
.start();
});

26 changes: 17 additions & 9 deletions src/server_manager/web_app/shadowbox_server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
// See the License for the specific language governing permissions and
// limitations under the License.

import * as semver from 'semver';

import * as errors from '../infrastructure/errors';
import * as server from '../model/server';

Expand Down Expand Up @@ -63,30 +65,36 @@ export class ShadowboxServer implements server.Server {
return this.apiRequest<void>('access-keys/' + accessKeyId, {method: 'DELETE'});
}

setAccessKeyDataLimit(limit: server.DataLimit): Promise<void> {
async setAccessKeyDataLimit(limit: server.DataLimit): Promise<void> {
console.info(`Setting access key data limit: ${JSON.stringify(limit)}`);
const requestOptions = {
method: 'PUT',
headers: new Headers({'Content-Type': 'application/json'}),
body: JSON.stringify({limit})
};
return this.apiRequest<void>('experimental/access-key-data-limit', requestOptions).then(() => {
this.serverConfig.accessKeyDataLimit = limit;
});
await this.apiRequest<void>(this.getAccessKeyDataLimitPath(), requestOptions);
this.serverConfig.accessKeyDataLimit = limit;
}

removeAccessKeyDataLimit(): Promise<void> {
async removeAccessKeyDataLimit(): Promise<void> {
console.info(`Removing access key data limit`);
return this.apiRequest<void>('experimental/access-key-data-limit', {method: 'DELETE'})
.then(() => {
delete this.serverConfig.accessKeyDataLimit;
});
await this.apiRequest<void>(this.getAccessKeyDataLimitPath(), {method: 'DELETE'});
delete this.serverConfig.accessKeyDataLimit;
}

getAccessKeyDataLimit(): server.DataLimit|undefined {
return this.serverConfig.accessKeyDataLimit;
}

private getAccessKeyDataLimitPath(): string {
const version = this.getVersion();
if (semver.gte(version, '1.3.0')) {
// Data limits became a permanent feature in shadowbox v1.3.0.
return 'server/access-key-data-limit';
}
return 'experimental/access-key-data-limit';
}

getDataUsage(): Promise<server.DataUsageByAccessKey> {
return this.apiRequest<server.DataUsageByAccessKey>('metrics/transfer');
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -142,12 +142,9 @@ Polymer({
cursor: pointer;
background-color: #eee;
}
#data-limits-container .selection-container h3 {
font-weight: normal;
margin-bottom: 8px;
}
#data-limits-container .selection-container p {
margin: 0 0 24px 0;
width: 80%;
}
#data-limits-container .selection-container span {
display: block;
Expand Down Expand Up @@ -191,6 +188,35 @@ Polymer({
<paper-input readonly="" value="[[serverVersion]]" label="[[localize('settings-server-version')]]" hidden\$="[[!serverVersion]]" always-float-label="" maxlength="100"></paper-input>
</div>
</div>
<!-- Data limits -->
<div class="setting card-section" hidden\$="[[!supportsAccessKeyDataLimit]]">
<iron-icon class="setting-icon" icon="icons:perm-data-setting"></iron-icon>
<div id="data-limits-container">
<div class="selection-container">
<div class="content">
<h3>[[localize('data-limits')]]</h3>
<p>[[localize('data-limits-description')]]</p>
</div>
<!-- NOTE: The dropdown is not automatically sized to the button's width:
https://github.com/PolymerElements/paper-dropdown-menu/issues/229 -->
<paper-dropdown-menu no-label-float="" horizontal-align="left">
<paper-listbox slot="dropdown-content" selected="{{_computeDataLimitsEnabledName(isAccessKeyDataLimitEnabled)}}" attr-for-selected="name" on-selected-changed="_accessKeyDataLimitEnabledChanged">
<paper-item name="enabled">[[localize('enabled')]]</paper-item>
<paper-item name="disabled">[[localize('disabled')]]</paper-item>
</paper-listbox>
</paper-dropdown-menu>
</div>
<div class="data-limits-input" hidden\$="[[!isAccessKeyDataLimitEnabled]]">
<paper-input id="accessKeyDataLimitInput" value="[[accessKeyDataLimit.value]]" label="Data limit per key" always-float-label="" allowed-pattern="[0-9]+" required="" auto-validate="" maxlength="9" on-keydown="_handleAccessKeyDataLimitInputKeyDown" on-blur="_requestSetAccessKeyDataLimit"></paper-input>
<paper-dropdown-menu no-label-float="">
<paper-listbox id="accessKeyDataLimitUnits" slot="dropdown-content" selected="[[accessKeyDataLimit.unit]]" attr-for-selected="name" on-selected-changed="_requestSetAccessKeyDataLimit">
<paper-item name="MB">MB</paper-item>
<paper-item name="GB">GB</paper-item>
</paper-listbox>
</paper-dropdown-menu>
</div>
</div>
</div>
<!-- Experiments -->
<div id="experiments" class="setting card-section" hidden\$="[[!shouldShowExperiments]]">
<iron-icon class="setting-icon" icon="icons:build"></iron-icon>
Expand All @@ -201,34 +227,6 @@ Polymer({
<iron-icon icon="icons:error-outline"></iron-icon>
<p inner-h-t-m-l="[[localize('experiments-disclaimer', 'openLink', '<a href=https://s3.amazonaws.com/outline-vpn/index.html#/en/support/dataCollection>', 'closeLink', '</a>')]]"></p>
</div>
<div id="data-limits-container" hidden\$="[[!supportsAccessKeyDataLimit]]">
<div class="selection-container">
<div class="content">
<h3>[[localize('data-limits')]]</h3>
<p>
[[localize('data-limits-description', 'date', dataLimitsAvailabilityDate)]]<br>
<span inner-h-t-m-l="[[localize('experiments-feedback', 'openLink', '<a href=https://docs.google.com/forms/d/e/1FAIpQLSfP7q9GnJCQyWMpFTLd9zwCm7cvUa-2NR8a8SznwMSbuRnrWg/viewform>', 'closeLink', '</a>')]]"></span>
</p>
</div>
<!-- NOTE: The dropdown is not automatically sized to the button's width:
https://github.com/PolymerElements/paper-dropdown-menu/issues/229 -->
<paper-dropdown-menu no-label-float="" horizontal-align="left">
<paper-listbox slot="dropdown-content" selected="{{_computeDataLimitsEnabledName(isAccessKeyDataLimitEnabled)}}" attr-for-selected="name" on-selected-changed="_accessKeyDataLimitEnabledChanged">
<paper-item name="enabled">[[localize('enabled')]]</paper-item>
<paper-item name="disabled">[[localize('disabled')]]</paper-item>
</paper-listbox>
</paper-dropdown-menu>
</div>
<div class="data-limits-input" hidden\$="[[!isAccessKeyDataLimitEnabled]]">
<paper-input id="accessKeyDataLimitInput" value="[[accessKeyDataLimit.value]]" label="Data limit per key" always-float-label="" allowed-pattern="[0-9]+" required="" auto-validate="" maxlength="9" on-keydown="_handleAccessKeyDataLimitInputKeyDown" on-blur="_requestSetAccessKeyDataLimit"></paper-input>
<paper-dropdown-menu no-label-float="">
<paper-listbox id="accessKeyDataLimitUnits" slot="dropdown-content" selected="[[accessKeyDataLimit.unit]]" attr-for-selected="name" on-selected-changed="_requestSetAccessKeyDataLimit">
<paper-item name="MB">MB</paper-item>
<paper-item name="GB">GB</paper-item>
</paper-listbox>
</paper-dropdown-menu>
</div>
</div>
</div>
</div>
<!-- Metrics controls -->
Expand Down Expand Up @@ -264,16 +262,13 @@ Polymer({
accessKeyDataLimit: {type: Object, value: null}, // type: app.DisplayDataAmount
supportsAccessKeyDataLimit:
{type: Boolean, value: false}, // Whether the server supports data limits.
dataLimitsAvailabilityDate:
{type: String}, // Date by which the feature stops being an experiment.
isHostnameEditable: {type: Boolean, value: true},
serverCreationDate: {type: String, value: null},
serverLocation: {type: String, value: null},
serverMonthlyCost: {type: String, value: null},
serverMonthlyTransferLimit: {type: String, value: null},
localize: {type: Function, readonly: true},
shouldShowExperiments:
{type: Boolean, computed: '_computeShouldShowExperiments(supportsAccessKeyDataLimit)'},
shouldShowExperiments: {type: Boolean, value: false},
},

setServerName: function(name) {
Expand Down Expand Up @@ -346,10 +341,6 @@ Polymer({
return isAccessKeyDataLimitEnabled ? 'enabled' : 'disabled';
},

_computeShouldShowExperiments: function(supportsAccessKeyDataLimit) {
return supportsAccessKeyDataLimit;
},

_validatePort: function(value) {
const port = Number(value);
const valid = !Number.isNaN(port) && port >= 1 && port <= 65535 && Number.isInteger(port);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -546,7 +546,7 @@ export class ServerView extends DirMixin(PolymerElement) {
</div>
</div>
<div name="settings">
<outline-server-settings id="serverSettings" server-id="[[serverId]]" server-hostname="[[serverHostname]]" server-name="[[serverName]]" server-version="[[serverVersion]]" is-hostname-editable="[[isHostnameEditable]]" server-management-api-url="[[serverManagementApiUrl]]" server-port-for-new-access-keys="[[serverPortForNewAccessKeys]]" is-access-key-port-editable="[[isAccessKeyPortEditable]]" access-key-data-limit="{{accessKeyDataLimit}}" is-access-key-data-limit-enabled="{{isAccessKeyDataLimitEnabled}}" data-limits-availability-date="[[dataLimitsAvailabilityDate]]" supports-access-key-data-limit="[[supportsAccessKeyDataLimit]]" server-creation-date="[[serverCreationDate]]" server-monthly-cost="[[monthlyCost]]" server-monthly-transfer-limit="[[_formatBytesTransferred(monthlyOutboundTransferBytes)]]" is-server-managed="[[isServerManaged]]" server-location="[[serverLocation]]" metrics-enabled="[[metricsEnabled]]" localize="[[localize]]">
<outline-server-settings id="serverSettings" server-id="[[serverId]]" server-hostname="[[serverHostname]]" server-name="[[serverName]]" server-version="[[serverVersion]]" is-hostname-editable="[[isHostnameEditable]]" server-management-api-url="[[serverManagementApiUrl]]" server-port-for-new-access-keys="[[serverPortForNewAccessKeys]]" is-access-key-port-editable="[[isAccessKeyPortEditable]]" access-key-data-limit="{{accessKeyDataLimit}}" is-access-key-data-limit-enabled="{{isAccessKeyDataLimitEnabled}}" supports-access-key-data-limit="[[supportsAccessKeyDataLimit]]" server-creation-date="[[serverCreationDate]]" server-monthly-cost="[[monthlyCost]]" server-monthly-transfer-limit="[[_formatBytesTransferred(monthlyOutboundTransferBytes)]]" is-server-managed="[[isServerManaged]]" server-location="[[serverLocation]]" metrics-enabled="[[metricsEnabled]]" localize="[[localize]]">
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: should we reformat this across across several lines? It's difficult for me to read on my laptop screen.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We lost the formatting during the polymer upgrade. We should look into a way of automating formatting for these mixed (html + css + js) files.

</outline-server-settings>
</div>
</iron-pages>
Expand Down Expand Up @@ -591,7 +591,6 @@ export class ServerView extends DirMixin(PolymerElement) {
accessKeyDataLimit: {type: Object},
isAccessKeyDataLimitEnabled: {type: Boolean},
supportsAccessKeyDataLimit: {type: Boolean},
dataLimitsAvailabilityDate: {type: String},
isServerManaged: Boolean,
isServerReachable: Boolean,
retryDisplayingServer: Function,
Expand Down Expand Up @@ -640,8 +639,6 @@ export class ServerView extends DirMixin(PolymerElement) {
this.isAccessKeyDataLimitEnabled = false;
/** Whether the server supports data limits. */
this.supportsAccessKeyDataLimit = false;
/** Date by which the feature stops being an experiment. */
this.dataLimitsAvailabilityDate = '';
this.isServerManaged = false;
this.isServerReachable = false;
/**
Expand Down
2 changes: 1 addition & 1 deletion src/shadowbox/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "outline-server",
"private": true,
"version": "1.2.3",
"version": "1.3.0",
"description": "Outline server",
"main": "build/server/main.js",
"author": "Outline",
Expand Down
18 changes: 15 additions & 3 deletions src/shadowbox/server/manager_service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,10 @@ export function bindService(
apiServer: restify.Server, apiPrefix: string, service: ShadowsocksManagerService) {
apiServer.put(`${apiPrefix}/name`, service.renameServer.bind(service));
apiServer.get(`${apiPrefix}/server`, service.getServer.bind(service));
apiServer.put(
`${apiPrefix}/server/access-key-data-limit`, service.setAccessKeyDataLimit.bind(service));
apiServer.del(
`${apiPrefix}/server/access-key-data-limit`, service.removeAccessKeyDataLimit.bind(service));
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wonder if it's good to model features as a resource like we do with access keys (/server/features/). That would be similar to /experimental/ url part we have.

Ideally, I think it would be nice to have something broken down by component like:

  • /server/access-key/keys/:id
  • /server/access-key/features/:id
  • /server/access-key/custom-methods

But that might not be possible to shoehorn to our current scheme.

https://google.aip.dev/

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In a way we already do this: the access key data limit is a property of the server (resource). I like the idea of formalizing the hierarchy.

apiServer.put(
`${apiPrefix}/server/hostname-for-access-keys`,
service.setHostnameForAccessKeys.bind(service));
Expand All @@ -94,13 +98,21 @@ export function bindService(
apiServer.get(`${apiPrefix}/metrics/enabled`, service.getShareMetrics.bind(service));
apiServer.put(`${apiPrefix}/metrics/enabled`, service.setShareMetrics.bind(service));

// Experimental APIs
// Redirect former experimental APIs
apiServer.put(
`${apiPrefix}/experimental/access-key-data-limit`,
service.setAccessKeyDataLimit.bind(service));
redirect(`${apiPrefix}/server/access-key-data-limit`));
apiServer.del(
`${apiPrefix}/experimental/access-key-data-limit`,
service.removeAccessKeyDataLimit.bind(service));
redirect(`${apiPrefix}/server/access-key-data-limit`));
}

// Returns a request handler that redirects a bound request path to `url` with HTTP status `code`.
function redirect(url: string, code = 301): restify.RequestHandlerType {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please use 308 instead to preserve the HTTP method.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since you never pass a different code, maybe remove it?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.

return (req: restify.Request, res: restify.Response, next: restify.Next) => {
logging.debug(`Redirecting ${req.url} => ${url} with ${code}`);
res.redirect(code, url, next);
};
}

function validateAccessKeyId(accessKeyId: unknown): string {
Expand Down