Skip to content

Commit

Permalink
Implement value reservation & locks
Browse files Browse the repository at this point in the history
  • Loading branch information
novemberborn committed Sep 27, 2020
1 parent b0a666d commit f6e29ff
Show file tree
Hide file tree
Showing 23 changed files with 724 additions and 0 deletions.
15 changes: 15 additions & 0 deletions .c8rc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"all": true,
"include": [
"{dist/source,source}/**/*.{js,ts}"
],
"exclude": [
"{coverage,dist/test}/**",
"{dist,source}/**/*.d.ts",
"*.config.js"
],
"reporter": [
"html",
"lcov"
]
}
12 changes: 12 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
root = true

[*]
indent_style = tab
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true

[*.yml]
indent_style = space
indent_size = 2
76 changes: 76 additions & 0 deletions .github/CODE_OF_CONDUCT.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
# Contributor Covenant Code of Conduct

Translations: [Español](https://github.com/avajs/ava-docs/blob/master/es_ES/code-of-conduct.md), [Français](https://github.com/avajs/ava-docs/blob/master/fr_FR/code-of-conduct.md), [Italiano](https://github.com/avajs/ava-docs/blob/master/it_IT/code-of-conduct.md), [日本語](https://github.com/avajs/ava-docs/blob/master/ja_JP/code-of-conduct.md), [Português](https://github.com/avajs/ava-docs/blob/master/pt_BR/code-of-conduct.md), [Русский](https://github.com/avajs/ava-docs/blob/master/ru_RU/code-of-conduct.md), [简体中文](https://github.com/avajs/ava-docs/blob/master/zh_CN/code-of-conduct.md)

## Our Pledge

In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to making participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, gender identity and expression, level of experience,
nationality, personal appearance, race, religion, or sexual identity and
orientation.

## Our Standards

Examples of behavior that contributes to creating a positive environment
include:

* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members

Examples of unacceptable behavior by participants include:

* The use of sexualized language or imagery and unwelcome sexual attention or
advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic
address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting

## Our Responsibilities

Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.

Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.

## Scope

This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community. Examples of
representing a project or community include using an official project e-mail
address, posting via an official social media account, or acting as an appointed
representative at an online or offline event. Representation of a project may be
further defined and clarified by project maintainers.

## Enforcement

Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at sindresorhus@gmail.com. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.

Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.

## Attribution

This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at [http://contributor-covenant.org/version/1/4][version]

[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/4/
7 changes: 7 additions & 0 deletions .github/CONTRIBUTING.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# Contributing to AVA

✨ Thanks for contributing to AVA! ✨

Please note that this project is released with a [Contributor Code of Conduct](CODE_OF_CONDUCT.md). By participating in this project you agree to abide by its terms.

This repository is a part of AVA. Start with reading AVA's [contributing guide](https://github.com/avajs/ava/blob/master/.github/CONTRIBUTING.md). Issue labels may be a little different in this repository but otherwise the same applies.
15 changes: 15 additions & 0 deletions .github/ISSUE_TEMPLATE/bug.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
---
name: Bug Report
about: If something isn't working the way you expect it to
labels: needs triage
---

Please provide details about:

* What you're trying to do
* What happened
* What you expected to happen

Please share relevant sample code. Or better yet, provide a link to a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example).

We'll also need your AVA configuration (in `package.json` or `ava.config.*` configuration files) and how you're invoking AVA. Share the installed AVA version (get it by running `npx ava --version`).
8 changes: 8 additions & 0 deletions .github/ISSUE_TEMPLATE/config.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
blank_issues_enabled: true
contact_links:
- name: AVA on Spectrum
url: https://spectrum.chat/ava
about: Ask questions and discuss in our Spectrum community
- name: Stack Overflow
url: https://stackoverflow.com/questions/tagged/ava
about: Tag your question on Stack Overflow
11 changes: 11 additions & 0 deletions .github/ISSUE_TEMPLATE/feature.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
---
name: Feature Request
about: Suggestions for new or different behavior
labels: question
---

Please provide details about:

* What you're trying to do
* Why you can't use this plugin for this
* And maybe how you think AVA could handle this
29 changes: 29 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
name: Install and test @ava/cooperate
on:
push:
branches:
- master
pull_request:
paths-ignore:
- "*.md"
jobs:
nodejs:
name: Node.js
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
node-version: [^12.17.0, ^14.0.0]
steps:
- uses: actions/checkout@v1
with:
fetch-depth: 1
- uses: actions/setup-node@v1
with:
node-version: ${{ matrix.node-version }}
- run: npm install --no-audit
- run: npm test
- uses: codecov/codecov-action@v1
with:
file: coverage/lcov.info
name: ${{ matrix.node-version }}
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
coverage
dist
node_modules
1 change: 1 addition & 0 deletions .npmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
package-lock=false
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# @ava/cooperate

Experimental AVA plugin to enable cooperation between test files.
11 changes: 11 additions & 0 deletions ava.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
export default { // eslint-disable-line import/no-anonymous-default-export
files: ['!dist/**'],
nonSemVerExperiments: {
sharedWorkers: true
},
typescript: {
rewritePaths: {
'test/': 'dist/test/'
}
}
};
46 changes: 46 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
{
"name": "@ava/cooperate",
"version": "0.0.0",
"description": "Plugin to enable cooperation between AVA test files",
"engines": {
"node": ">=12.17.0 <13 || >=14.0.0"
},
"files": [
"dist/source",
"source",
"!dist/source/worker.d.ts"
],
"main": "dist/source",
"types": "dist/source",
"scripts": {
"build": "del-cli dist && tsc",
"prepare": "npm run -s build",
"test": "xo && c8 ava"
},
"keywords": [
"ava",
"lock",
"mutex",
"plugin",
"test"
],
"author": "Mark Wubben (https://novemberborn.net)",
"repository": "avajs/cooperate",
"license": "MIT",
"devDependencies": {
"@ava/typescript": "^1.1.1",
"@sindresorhus/tsconfig": "^0.7.0",
"ava": "^3.13.0",
"c8": "^7.3.1",
"del-cli": "^3.0.1",
"delay": "^4.4.0",
"typescript": "^4.0.3",
"xo": "^0.33.1"
},
"dependencies": {
"never": "^1.0.2"
},
"peerDependencies": {
"ava": "*"
}
}
109 changes: 109 additions & 0 deletions source/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
import path from 'path';
import {registerSharedWorker} from 'ava/plugin';
import never from 'never';

import {Data, MessageType} from './types';

const protocol = registerSharedWorker<Data>({
filename: path.join(__dirname, 'worker.js'),
supportedProtocols: ['experimental']
});

export class Lock {
readonly #context: SharedContext;

constructor(context: SharedContext, public readonly id: string) {
this.#context = context;
}

async acquire(): Promise<() => void> {
// Allow reserve() to be called before the shared worker is availabe.
await protocol.available;

const message = protocol.publish({
type: MessageType.LOCK,
contextId: this.#context.id,
lockId: this.id,
wait: true
});

for await (const reply of message.replies()) {
if (reply.data.type === MessageType.LOCK_ACQUIRED) {
return () => {
reply.reply({type: MessageType.LOCK_RELEASE});
};
}
}

/* c8 ignore next 2 */
// The above loop will never actually break if the lock is not acquired.
return never();
}

async acquireNow(): Promise<() => void> {
// Publish immediately, which will fail if the protocol is not available.
// "Now" should not mean "wait until we're ready."

const message = protocol.publish({
type: MessageType.LOCK,
contextId: this.#context.id,
lockId: this.id,
wait: false
});

for await (const reply of message.replies()) {
if (reply.data.type === MessageType.LOCK_ACQUIRED) {
return () => {
reply.reply({type: MessageType.LOCK_RELEASE});
};
}

if (reply.data.type === MessageType.LOCK_FAILED) {
throw new LockAcquisitionError(this.id);
}
}

/* c8 ignore next 2 */
// The above loop will never actually break if the lock is not acquired.
return never();
}
}

export class LockAcquisitionError extends Error {
get name() {
return 'LockAcquisitionError';
}

constructor(public readonly lockId: string) {
super('Could not immediately acquire the lock');
}
}

export class SharedContext {
constructor(public readonly id: string) {}

createLock(id: string): Lock {
return new Lock(this, id);
}

async reserve<T extends bigint | number | string>(...values: T[]): Promise<T[]> {
// Allow reserve() to be called before the shared worker is availabe.
await protocol.available;

const message = protocol.publish({
type: MessageType.RESERVE,
contextId: this.id,
values
});

for await (const {data} of message.replies()) {
if (data.type === MessageType.RESERVED_INDEXES) {
return data.indexes.map(index => values[index]);
}
}

/* c8 ignore next 2 */
// The above loop will never actually break if the lock is not acquired.
return never();
}
}
38 changes: 38 additions & 0 deletions source/types.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
export const enum MessageType {
LOCK = 10,
LOCK_ACQUIRED = 11,
LOCK_FAILED = 12,
LOCK_RELEASE = 13,
RESERVE = 20,
RESERVED_INDEXES = 21,
}

export type Lock = {
type: MessageType.LOCK;
contextId: string;
lockId: string;
wait: boolean;
};

export type Locked = {
type: MessageType.LOCK_ACQUIRED | MessageType.LOCK_FAILED;
};

export type LockRelease = {
type: MessageType.LOCK_RELEASE;
};

export type Reservation = {
type: MessageType.RESERVE;
contextId: string;
values: Array<bigint | number | string>;
};

export type ReservedIndexes = {
type: MessageType.RESERVED_INDEXES;
indexes: number[];
};

export type Data =
Lock | Locked | LockRelease |
Reservation | ReservedIndexes;

0 comments on commit f6e29ff

Please sign in to comment.