@ackstate/js-sdk 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 AckState
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,76 @@
1
+ # AckState JavaScript SDK
2
+
3
+ ### **An event is a fact: it exists once received, is seen once delivered, and is done only when acknowledged.**
4
+
5
+ ### Install
6
+ ```bash
7
+ npm install @ackstate/js-sdk
8
+ ```
9
+
10
+ ### Basic Usage
11
+
12
+ ```javascript
13
+ import { Inbox, LeaseLostError, NetworkError } from "@ackstate/js-sdk";
14
+
15
+ const inbox = new Inbox({
16
+ apiKey: process.env.ACK_STATE_API_KEY,
17
+ projectId: "proj_123",
18
+ consumerId: "worker-1",
19
+ });
20
+
21
+ async function run() {
22
+ while (true) { // or your long running process condition
23
+
24
+ const event = await inbox.next();
25
+ if (!event) break;
26
+
27
+ try {
28
+ // event.body is raw bytes — parse only if you need to
29
+ const payload = JSON.parse(event.body.toString("utf8"));
30
+
31
+ await handleBusinessLogic(payload);
32
+
33
+ await inbox.ack(event);
34
+ } catch (err) {
35
+ if (err instanceof LeaseLostError) {
36
+ // Another worker took over. Do nothing.
37
+ return;
38
+ }
39
+
40
+ if (err instanceof NetworkError) {
41
+ // Optional: crash or retry at process level
42
+ throw err;
43
+ }
44
+
45
+ await inbox.fail(event, err instanceof Error ? err.message : undefined);
46
+ }
47
+ }
48
+ }
49
+
50
+ run().catch(console.error);
51
+ ```
52
+
53
+ ### Note
54
+ - Each pulled event with `inbox.next()` gets leased for 5 seconds
55
+ - In this lease period, `inbox.ack()` or `inbox.fail()` is expected
56
+ - If the event wasn't acked or failed, it will be eligible to be pulled again
57
+
58
+ ### Guarantees
59
+
60
+ - "An event is delivered to only one consumer at a time"
61
+ - "Events are acknowledged only after successful processing"
62
+ - "Failed events are retried safely"
63
+ - "Replay is explicit and intentional"
64
+ - "The SDK never hides state or guesses outcomes"
65
+
66
+ ### What This SDK Does Not Do
67
+ - Retry your business logic
68
+ - Auto-extend leases
69
+ - Parse payloads
70
+ - Hide failures
71
+ - Infer success
72
+
73
+ ### API Reference
74
+
75
+ For detailed API documentation, see [API_REFERENCE.md](API_REFERENCE.md).
76
+
package/package.json ADDED
@@ -0,0 +1,28 @@
1
+ {
2
+ "name": "@ackstate/js-sdk",
3
+ "version": "0.1.0",
4
+ "description": "Lightweight JavaScript SDK for ackstate event delivery & tracking",
5
+ "main": "src/index.js",
6
+ "exports": {
7
+ ".": "./src/index.js"
8
+ },
9
+ "type": "module",
10
+ "files": ["src"],
11
+ "scripts": {},
12
+ "dependencies": {
13
+ "undici": "^6.0.0"
14
+ },
15
+ "engines": {
16
+ "node": ">=18"
17
+ },
18
+ "keywords": ["ackstate", "events", "webhooks", "ingest", "sdk"],
19
+ "license": "MIT",
20
+ "repository": {
21
+ "type": "git",
22
+ "url": "git+https://github.com/hussam-salah/ackstate-js-sdk.git"
23
+ },
24
+ "homepage": "https://github.com/hussam-salah/ackstate-js-sdk#readme",
25
+ "bugs": {
26
+ "url": "https://github.com/hussam-salah/ackstate-js-sdk/issues"
27
+ }
28
+ }
package/src/errors.js ADDED
@@ -0,0 +1,5 @@
1
+ export class AuthError extends Error {}
2
+ export class NetworkError extends Error {}
3
+ export class LeaseLostError extends Error {}
4
+ export class StateViolationError extends Error {}
5
+ export class NotFoundError extends Error {}
package/src/event.js ADDED
@@ -0,0 +1,5 @@
1
+ export function freezeEvent(event) {
2
+ Object.freeze(event.headers);
3
+ Object.freeze(event);
4
+ return event;
5
+ }
package/src/http.js ADDED
@@ -0,0 +1,115 @@
1
+ import { request } from "undici";
2
+ import {
3
+ AuthError,
4
+ NetworkError,
5
+ LeaseLostError,
6
+ NotFoundError,
7
+ } from "./errors.js";
8
+
9
+ const API_BASE = "https://api.ackstate.com/v1";
10
+
11
+ async function handleResponse(res) {
12
+ if (res.statusCode === 401 || res.statusCode === 403) {
13
+ throw new AuthError("Invalid API credentials");
14
+ }
15
+
16
+ if (res.statusCode === 404) {
17
+ throw new NotFoundError("Resource not found");
18
+ }
19
+
20
+ if (res.statusCode === 409) {
21
+ throw new LeaseLostError("Lease lost");
22
+ }
23
+
24
+ if (res.statusCode >= 400) {
25
+ throw new NetworkError(`HTTP ${res.statusCode}`);
26
+ }
27
+
28
+ return res;
29
+ }
30
+
31
+ export async function getNextEvent(apiKey, projectId, consumerId) {
32
+ try {
33
+ const params = new URLSearchParams({
34
+ projectId,
35
+ consumerId,
36
+ });
37
+
38
+ const res = await request(`${API_BASE}/events/next?${params.toString()}`, {
39
+ method: "GET",
40
+ headers: {
41
+ Authorization: `Bearer ${apiKey}`,
42
+ },
43
+ });
44
+
45
+ if (res.statusCode === 204) return null;
46
+
47
+ await handleResponse(res);
48
+
49
+ const text = await res.body.text();
50
+ if (!text) return null;
51
+
52
+ return JSON.parse(text);
53
+ } catch (err) {
54
+ if (err instanceof Error) throw err;
55
+ throw new NetworkError("Network failure");
56
+ }
57
+ }
58
+
59
+ export async function ackEvent(apiKey, consumerId, eventId) {
60
+ try {
61
+ const params = new URLSearchParams({
62
+ consumerId,
63
+ });
64
+
65
+ const res = await request(`${API_BASE}/events/${eventId}/ack?${params.toString()}`, {
66
+ method: "POST",
67
+ headers: {
68
+ Authorization: `Bearer ${apiKey}`,
69
+ },
70
+ });
71
+
72
+ await handleResponse(res);
73
+ } catch (err) {
74
+ if (err instanceof Error) throw err;
75
+ throw new NetworkError("Network failure");
76
+ }
77
+ }
78
+
79
+ export async function failEvent(apiKey, consumerId, eventId, reason) {
80
+ try {
81
+ const params = new URLSearchParams({
82
+ consumerId,
83
+ });
84
+
85
+ const res = await request(`${API_BASE}/events/${eventId}/fail?${params.toString()}`, {
86
+ method: "POST",
87
+ headers: {
88
+ Authorization: `Bearer ${apiKey}`,
89
+ "Content-Type": "application/json",
90
+ },
91
+ body: JSON.stringify({ reason }),
92
+ });
93
+
94
+ await handleResponse(res);
95
+ } catch (err) {
96
+ if (err instanceof Error) throw err;
97
+ throw new NetworkError("Network failure");
98
+ }
99
+ }
100
+
101
+ export async function replayEvent(apiKey, eventId) {
102
+ try {
103
+ const res = await request(`${API_BASE}/events/${eventId}/replay`, {
104
+ method: "POST",
105
+ headers: {
106
+ Authorization: `Bearer ${apiKey}`,
107
+ },
108
+ });
109
+
110
+ await handleResponse(res);
111
+ } catch (err) {
112
+ if (err instanceof Error) throw err;
113
+ throw new NetworkError("Network failure");
114
+ }
115
+ }
package/src/inbox.js ADDED
@@ -0,0 +1,81 @@
1
+ import { freezeEvent } from "./event.js";
2
+ import {
3
+ getNextEvent,
4
+ ackEvent,
5
+ failEvent,
6
+ replayEvent,
7
+ } from "./http.js";
8
+ import { StateViolationError } from "./errors.js";
9
+
10
+ export class Inbox {
11
+ #activeEventIds = new Set();
12
+ #config;
13
+
14
+ constructor(config) {
15
+ this.#config = config;
16
+ this.validateConfig(config);
17
+ }
18
+
19
+ async next() {
20
+ const res = await getNextEvent(
21
+ this.#config.apiKey,
22
+ this.#config.projectId,
23
+ this.#config.consumerId
24
+ );
25
+
26
+ if (!res) return null;
27
+
28
+ const event = {
29
+ id: res.event.id,
30
+ headers: res.event.headers,
31
+ body: Buffer.from(res.event.body, "base64"),
32
+ receivedAt: res.event.received_at,
33
+ leasedAt: res.event.leased_at,
34
+ expiresAt: res.event.expires_at,
35
+ };
36
+
37
+ this.#activeEventIds.add(event.id);
38
+ return freezeEvent(event);
39
+ }
40
+
41
+ async ack(event) {
42
+ if (!this.#activeEventIds.has(event.id)) {
43
+ throw new StateViolationError("No active lease for this event");
44
+ }
45
+
46
+ await ackEvent(this.#config.apiKey, this.#config.consumerId, event.id);
47
+ this.#activeEventIds.delete(event.id);
48
+ }
49
+
50
+ async fail(event, reason) {
51
+ if (!this.#activeEventIds.has(event.id)) {
52
+ throw new StateViolationError("No active lease for this event");
53
+ }
54
+
55
+ await failEvent(
56
+ this.#config.apiKey,
57
+ this.#config.consumerId,
58
+ event.id,
59
+ reason
60
+ );
61
+ this.#activeEventIds.delete(event.id);
62
+ }
63
+
64
+ async replay(eventId) {
65
+ await replayEvent(this.#config.apiKey, eventId);
66
+ }
67
+
68
+ validateConfig(config) {
69
+ if (!config.apiKey?.trim()) {
70
+ throw new Error("apiKey is required and cannot be empty");
71
+ }
72
+
73
+ if (!config.projectId?.trim()) {
74
+ throw new Error("projectId is required and cannot be empty");
75
+ }
76
+
77
+ if (!config.consumerId?.trim()) {
78
+ throw new Error("consumerId is required and cannot be empty");
79
+ }
80
+ }
81
+ }
package/src/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export { Inbox } from "./inbox.js";
2
+ export * from "./errors.js";