Skip to content

Commit 145b31b

Browse files
add some implementation stuff
1 parent 80d4e06 commit 145b31b

File tree

8 files changed

+296
-0
lines changed

8 files changed

+296
-0
lines changed

.gitignore

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
/tsconfig.tsbuildinfo
2+
/lib
3+
/node_modules

package-lock.json

Lines changed: 29 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
{
2+
"private": true,
3+
"name": "proposal-concurrency-control",
4+
"version": "1.0.0",
5+
"description": "",
6+
"main": "lib/index.js",
7+
"type": "module",
8+
"scripts": {
9+
"build": "tsc",
10+
"test": "node --test"
11+
},
12+
"repository": {
13+
"type": "git",
14+
"url": "git+ssh://git@github.com/michaelficarra/proposal-concurrency-control.git"
15+
},
16+
"author": "Michael Ficarra",
17+
"bugs": {
18+
"url": "https://github.com/michaelficarra/proposal-concurrency-control/issues"
19+
},
20+
"homepage": "https://github.com/michaelficarra/proposal-concurrency-control#readme",
21+
"devDependencies": {
22+
"typescript": "5.5.3"
23+
},
24+
"dependencies": {
25+
}
26+
}

src/auto.ts

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
2+
import { Governor, Semaphore } from "./index.js";
3+
4+
Object.defineProperty(globalThis, "Governor", {
5+
configurable: true,
6+
writable: true,
7+
enumerable: false,
8+
value: Governor,
9+
});
10+
11+
Object.defineProperty(globalThis, "Semaphore", {
12+
configurable: true,
13+
writable: true,
14+
enumerable: false,
15+
value: Semaphore,
16+
});

src/governor.ts

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
export abstract class Governor {
2+
abstract acquire(): Promise<GovernorToken>;
3+
4+
with<R>(fn: (...args: []) => R): Promise<Awaited<R>> {
5+
return this.wrap(fn)();
6+
}
7+
8+
wrap<T, A extends unknown[], R>(fn: (this: T, ...args: A) => R): ((this: T, ...args: A) => Promise<Awaited<R>>) {
9+
const _this = this;
10+
return async function(...args): Promise<Awaited<R>> {
11+
const token = await _this.acquire();
12+
try {
13+
return await fn.apply(this, args);
14+
} finally {
15+
token[Symbol.dispose]();
16+
}
17+
};
18+
}
19+
20+
wrapIterator<T>(iter: Iterator<T> | AsyncIterator<T>): AsyncIterator<T> {
21+
const _this = this;
22+
return {
23+
next: async function(n) {
24+
return await _this.wrap(iter.next as Iterator<T>['next']).call(iter, n);
25+
},
26+
return: async () =>
27+
typeof iter.return === "function"
28+
? iter.return()
29+
: { done: true, value: undefined }
30+
}
31+
}
32+
33+
// wrapIterable<T>(iter: Iterable<T> | AsyncIterable<T>): AsyncIterable<T> {
34+
// }
35+
}
36+
37+
export interface GovernorToken {
38+
release(): void;
39+
[Symbol.dispose](): void;
40+
}

src/index.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
export { Governor } from "./governor.js";
2+
export { Semaphore } from "./semaphore.js";
3+
export type { GovernorToken } from "./governor.ts";

src/semaphore.ts

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
import { Governor } from "./governor.js";
2+
3+
export class Semaphore extends Governor {
4+
#limit: number;
5+
#acquired: number = 0;
6+
#wait: PromiseWithResolvers<void> | null = null;
7+
#idleListeners: (() => void)[] = [];
8+
9+
constructor(limit: number) {
10+
if ((limit >>> 0) !== limit) {
11+
throw new TypeError("Limit must be an integer");
12+
}
13+
if (limit < 0) {
14+
throw new RangeError("Limit must be non-negative");
15+
}
16+
super();
17+
18+
this.#limit = limit;
19+
}
20+
21+
async acquire() {
22+
while (this.#acquired >= this.#limit) {
23+
if (!this.#wait) {
24+
this.#wait = Promise.withResolvers<void>();
25+
}
26+
await this.#wait.promise;
27+
}
28+
++this.#acquired;
29+
30+
let hasReleased = false;
31+
32+
const dispose = () => {
33+
if (hasReleased) {
34+
throw new Error("Already released");
35+
}
36+
hasReleased = true;
37+
--this.#acquired;
38+
if (this.#wait) {
39+
this.#wait.resolve();
40+
this.#wait = null;
41+
} else if (this.#acquired === 0) {
42+
this.#notifyIdleListeners();
43+
}
44+
};
45+
46+
return {
47+
release: dispose,
48+
[Symbol.dispose]: dispose,
49+
};
50+
}
51+
52+
addIdleListener(cb: () => void) {
53+
this.#idleListeners.push(cb);
54+
}
55+
56+
removeIdleListener(cb: () => void) {
57+
const idx = this.#idleListeners.indexOf(cb);
58+
if (idx >= 0) {
59+
this.#idleListeners.splice(idx, 1);
60+
}
61+
}
62+
63+
#notifyIdleListeners() {
64+
for (const cb of this.#idleListeners) {
65+
try {
66+
cb();
67+
} catch {}
68+
}
69+
}
70+
}

tsconfig.json

Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
{
2+
"compilerOptions": {
3+
/* Visit https://aka.ms/tsconfig to read more about this file */
4+
5+
/* Projects */
6+
"incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
7+
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
8+
// "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
9+
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
10+
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
11+
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
12+
13+
/* Language and Environment */
14+
"target": "esnext", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
15+
// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
16+
// "jsx": "preserve", /* Specify what JSX code is generated. */
17+
// "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */
18+
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
19+
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
20+
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
21+
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
22+
// "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
23+
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
24+
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
25+
// "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
26+
27+
/* Modules */
28+
"module": "esnext", /* Specify what module code is generated. */
29+
"rootDir": "src", /* Specify the root folder within your source files. */
30+
// "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */
31+
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
32+
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
33+
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
34+
// "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
35+
// "types": [], /* Specify type package names to be included without being referenced in a source file. */
36+
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
37+
// "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
38+
// "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */
39+
// "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */
40+
// "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */
41+
// "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
42+
// "resolveJsonModule": true, /* Enable importing .json files. */
43+
// "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */
44+
// "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
45+
46+
/* JavaScript Support */
47+
// "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
48+
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
49+
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
50+
51+
/* Emit */
52+
"declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
53+
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
54+
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
55+
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */
56+
"inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
57+
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
58+
"outDir": "lib", /* Specify an output folder for all emitted files. */
59+
"removeComments": true, /* Disable emitting comments. */
60+
// "noEmit": true, /* Disable emitting files from a compilation. */
61+
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
62+
// "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
63+
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
64+
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
65+
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
66+
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
67+
"emitBOM": false, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
68+
"newLine": "lf", /* Set the newline character for emitting files. */
69+
// "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
70+
// "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
71+
// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
72+
// "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
73+
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
74+
// "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
75+
76+
/* Interop Constraints */
77+
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
78+
// "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */
79+
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
80+
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
81+
"preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
82+
"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
83+
84+
/* Type Checking */
85+
"strict": true, /* Enable all strict type-checking options. */
86+
"noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
87+
"strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
88+
"strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
89+
"strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
90+
"strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
91+
"noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
92+
"useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
93+
"alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
94+
"noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
95+
"noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
96+
"exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
97+
"noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
98+
"noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
99+
"noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
100+
"noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
101+
"noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
102+
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
103+
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
104+
105+
/* Completeness */
106+
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
107+
"skipLibCheck": true /* Skip type checking all .d.ts files. */
108+
}
109+
}

0 commit comments

Comments
 (0)