@thingmate/zekta-time-series 0.1.0 → 1.0.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.
Files changed (66) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/CONTRIBUTING.md +99 -43
  3. package/README.md +230 -2
  4. package/package.json +27 -41
  5. package/src/bucket.private/helpers.private/temp-files/temp-files.d.ts +15 -0
  6. package/src/bucket.private/helpers.private/temp-files/temp-files.js +47 -0
  7. package/src/bucket.private/helpers.private/temp-files/temp-files.js.map +1 -0
  8. package/src/bucket.private/zekta-time-bucket.d.ts +80 -0
  9. package/src/bucket.private/zekta-time-bucket.js +504 -0
  10. package/src/bucket.private/zekta-time-bucket.js.map +1 -0
  11. package/src/config/v1/zekta-time-series-config-v1-schema.d.ts +11 -0
  12. package/src/config/v1/zekta-time-series-config-v1-schema.js +12 -0
  13. package/src/config/v1/zekta-time-series-config-v1-schema.js.map +1 -0
  14. package/src/config/v1/zekta-time-series-config-v1.d.ts +11 -0
  15. package/src/config/v1/zekta-time-series-config-v1.js +2 -0
  16. package/src/config/v1/zekta-time-series-config-v1.js.map +1 -0
  17. package/src/config/zekta-time-series-config.d.ts +6 -0
  18. package/src/config/zekta-time-series-config.js +2 -0
  19. package/src/config/zekta-time-series-config.js.map +1 -0
  20. package/{helpers.private → src/helpers.private}/binary-search/binary-search.js +1 -2
  21. package/src/helpers.private/binary-search/binary-search.js.map +1 -0
  22. package/{helpers.private → src/helpers.private}/handle-promise-all-settled-result.d.ts +6 -0
  23. package/{helpers.private → src/helpers.private}/handle-promise-all-settled-result.js +6 -0
  24. package/src/helpers.private/handle-promise-all-settled-result.js.map +1 -0
  25. package/{helpers.private → src/helpers.private}/resizeable-buffer.d.ts +6 -0
  26. package/{helpers.private → src/helpers.private}/resizeable-buffer.js +7 -3
  27. package/src/helpers.private/resizeable-buffer.js.map +1 -0
  28. package/src/helpers.private/safe-write-file/safe-write-file.d.ts +13 -0
  29. package/src/helpers.private/safe-write-file/safe-write-file.js +29 -0
  30. package/src/helpers.private/safe-write-file/safe-write-file.js.map +1 -0
  31. package/src/helpers.private/throw-if-time-is-invalid/throw-if-time-is-invalid.d.ts +6 -0
  32. package/src/helpers.private/throw-if-time-is-invalid/throw-if-time-is-invalid.js +11 -0
  33. package/src/helpers.private/throw-if-time-is-invalid/throw-if-time-is-invalid.js.map +1 -0
  34. package/{index.d.ts → src/index.d.ts} +3 -1
  35. package/src/index.js +8 -0
  36. package/src/index.js.map +1 -0
  37. package/{specializations → src/specializations}/bytes/zekta-bytes-time-series.d.ts +21 -1
  38. package/src/specializations/bytes/zekta-bytes-time-series.js +152 -0
  39. package/src/specializations/bytes/zekta-bytes-time-series.js.map +1 -0
  40. package/src/specializations/number/zekta-number-time-series.d.ts +51 -0
  41. package/{specializations → src/specializations}/number/zekta-number-time-series.js +32 -11
  42. package/src/specializations/number/zekta-number-time-series.js.map +1 -0
  43. package/src/specializations/text/zekta-text-time-series.d.ts +36 -0
  44. package/{specializations → src/specializations}/text/zekta-text-time-series.js +20 -2
  45. package/src/specializations/text/zekta-text-time-series.js.map +1 -0
  46. package/src/zekta-time-series.d.ts +78 -0
  47. package/src/zekta-time-series.js +280 -0
  48. package/src/zekta-time-series.js.map +1 -0
  49. package/helpers.private/binary-search/binary-search.js.map +0 -1
  50. package/helpers.private/handle-promise-all-settled-result.js.map +0 -1
  51. package/helpers.private/resizeable-buffer.js.map +0 -1
  52. package/index.js +0 -6
  53. package/index.js.map +0 -1
  54. package/specializations/bytes/zekta-bytes-time-series.js +0 -87
  55. package/specializations/bytes/zekta-bytes-time-series.js.map +0 -1
  56. package/specializations/number/zekta-number-time-series.d.ts +0 -20
  57. package/specializations/number/zekta-number-time-series.js.map +0 -1
  58. package/specializations/text/zekta-text-time-series.d.ts +0 -16
  59. package/specializations/text/zekta-text-time-series.js.map +0 -1
  60. package/zekta-time-bucket.d.ts +0 -35
  61. package/zekta-time-bucket.js +0 -324
  62. package/zekta-time-bucket.js.map +0 -1
  63. package/zekta-time-series.d.ts +0 -25
  64. package/zekta-time-series.js +0 -194
  65. package/zekta-time-series.js.map +0 -1
  66. /package/{helpers.private → src/helpers.private}/binary-search/binary-search.d.ts +0 -0
package/CHANGELOG.md ADDED
@@ -0,0 +1,22 @@
1
+ # @thingmate/zekta-time-series
2
+
3
+ ## 1.0.0 (2026-11-30)
4
+
5
+ ### Major Changes
6
+
7
+ - First stable release of the file-system backed time series library. ([#1](https://github.com/thingmate/zekta-time-series/pull/1))
8
+
9
+ - Added `compact()` on the bytes and text series: it removes the stored files no longer
10
+ referenced by any entry, reclaiming the storage of deleted values.
11
+ - Persistence is now crash-safe: bucket files are written atomically, pure appends and
12
+ truncations happen in place, and torn tails left by an interrupted write are repaired on the
13
+ next load. Leftover temp files are cleaned up when the series is opened.
14
+ - Faster writes: tail changes append in place and sorted batches are merged in a single pass
15
+ (~2.4x faster than `node:sqlite` on 1000-entry ingestion, ~7.8x on range reads, see the README
16
+ benchmarks).
17
+ - Hardened validation: rejected `push` and `insert` calls leave the series untouched (and store
18
+ no file), opening rejects invalid configurations instead of persisting them, bucket files are
19
+ validated on open, and buckets larger than ~1.5GB no longer risk silent truncation.
20
+ - Read-only operations no longer keep the process alive for an extra second.
21
+ - Full README (usage, on-disk layout, persistence and crash-safety contract, validation contract,
22
+ benchmarks) and a declared Node.js >= 24 requirement.
package/CONTRIBUTING.md CHANGED
@@ -1,75 +1,131 @@
1
1
  # Contributing
2
2
 
3
- This projet is open to everyone. Feel free to test the library, share it, improve it, and create merge requests.
3
+ This project is open to everyone. Feel free to test the library, share it, improve it, and create pull requests.
4
4
 
5
- ### Getting started
5
+ ## Getting started
6
6
 
7
- The library requires [Node.js](https://nodejs.org/en) `24+` and [yarn](https://yarnpkg.com/).
7
+ ### Tools
8
8
 
9
- First, we have to use the correct version of node:
9
+ #### [nvm](https://github.com/nvm-sh/nvm)
10
+
11
+ We recommend using [nvm](https://github.com/nvm-sh/nvm) to manage your Node.js versions.
10
12
 
11
13
  ```shell
12
- nvm use
14
+ curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.3/install.sh | bash
13
15
  ```
14
16
 
15
- If you don't have [nvm](https://github.com/nvm-sh/nvm), you may manually install and use Node.js 24+.
16
-
17
- Then, we have to use the proper package manager (here `yarn`):
17
+ #### [Node](https://nodejs.org)
18
18
 
19
19
  ```shell
20
- corepack enable
20
+ nvm use
21
+
22
+ # Verify the Node.js version:
23
+ node -v
21
24
  ```
22
25
 
23
- Start a local verdaccio:
26
+ #### [Yarn](https://yarnpkg.com)
24
27
 
25
28
  ```shell
26
- npx fabrique verdaccio
27
- ```
29
+ corepack enable yarn
28
30
 
29
- And install the dependencies:
31
+ # Verify Yarn version:
32
+ yarn -v
30
33
 
31
- ```shell
34
+ # Install the dependencies:
32
35
  yarn install
33
36
  ```
34
37
 
35
38
  ### Code
36
39
 
37
40
  - The source code is located in the `src` directory.
38
- - The projet uses [prettier](https://prettier.io/) to format the code. You'll want to enable and configure it in your IDE.
41
+ - The project uses [prettier](https://prettier.io/) to format the code. You'll want to enable and configure it in your IDE.
39
42
  - The tests run with [vitest](https://vitest.dev)
40
43
 
41
44
  ### Commands
42
45
 
43
46
  - `fb:build`: builds the library.
44
- - converts the typescript files into javascript files, copies the scss files, and assembles all the assets to create a package ready to be published.
47
+ - converts the TypeScript files into JavaScript files, copies the SCSS files, and assembles all the assets to create a package ready to be published.
45
48
  - some files are handled differently:
46
- - `*.protected.{ts,scss}` or `**/*.protected/**`: these files are exported under `package-name/protected`
47
- - this is indented to expose parts of the code that should be restricted to advanced users only, or shared to other libraries requiring _internal_ control.
49
+ - `*.protected.{ts,scss}` or `**/*.protected/**`: these files are exported under `package-name/protected`.
50
+ - this is intended to expose parts of the code that should be restricted to advanced users only, or shared with other libraries requiring _internal_ control.
48
51
  - `*.private.{ts,scss}` or `/*.private/**`: these files are **not** exported.
49
- - this is indented to consume parts of the code internally, and not expose them publicly.
52
+ - this is intended to consume parts of the code internally, without exposing them publicly.
50
53
  - `fb:format`: formats the code using `prettier`.
51
- - `fb:test`: runs the tests using `vitest`.
52
- - `fb:test:coverage`: runs the tests with coverage.
53
- - by default, 100% code coverage is required, to enforce good quality.
54
- - `fb:bench`: runs the bench tests.
55
- - `fb:typedoc`: generates the documentation.
56
- - if the library exposes publicly only a few and/or simple parts, the documentation may be defined in the `README.md` instead.
57
- - `fb:prod`: builds the lib in `prod` mode.
58
- - builds and publishes the lib on npm as a _prod_ version.
59
- - `fb:dev`: builds the lib in `dev` mode.
60
- - builds and publishes the lib on a local `verdaccio` with a `dev` tag.
61
- - a local `verdaccio` is used to debug/test your library in another project:
62
- - it is better than `npm link`, as it enforce a specific version, and allows some dependencies to be `dev` too.
63
- - `fb:rc`: builds the lib in `rc` mode.
64
- - builds and publishes the lib on npm with a `rc` tag.
65
- - to test before production and final release
66
-
67
- ### To create an MR
68
-
69
- 1. fork the repository
70
- 1. add the feature/fix by modifying the code in the `src/` directory
71
- 1. add/write some tests until 100% code coverage is reached (run the tests with `yarn fb:test:coverage`)
72
- 1. format the code, using the command `yarn fb:format`
73
- 1. commit and push your work following the [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/) convention
74
- 1. create an MR from your repository to the upstream repository, explaining clearly what was added/fixed.
75
54
 
55
+ ### To create a PR
56
+
57
+ 1. Fork the repository
58
+ 1. Add the feature or fix by modifying the code in the `src/` directory
59
+ 1. Add/write some tests with good code coverage (run them with `yarn fb:test:coverage`)
60
+ 1. Add a [changeset](https://github.com/changesets/changesets) in `.changeset/` if the PR affects the published package (or use the `generate-changeset` agent skill)
61
+ 1. Format the code using the command `yarn fb:format`
62
+ 1. Commit and push your work following the [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/) convention
63
+ 1. Create a PR from your fork to the upstream repository, clearly explaining what was added or fixed.
64
+
65
+ ## Release Workflow
66
+
67
+ > The `release.yml` workflow runs on `pull_request` and `push` events for the `main` and `develop` branches.
68
+ > It invokes `yarn fb:ci:release`, which builds and publishes the packages.
69
+ > Note that the `publish` step runs only if the equivalent stable version (`x.y.z`) does not already exist on npm.
70
+ > On `main`, the release also consumes the pending changesets and pushes the version bump commit back to the branch.
71
+
72
+ ### 1. Pull Request to `main` or `develop`
73
+
74
+ - The `dev` label is added to the PR
75
+ - Impacted packages are published as: `x.y.z-dev.<timestamp>`
76
+ - npm dist-tag: `dev`
77
+
78
+ > Use the `dev` versions only if required.
79
+
80
+ > [!NOTE]
81
+ > The PR is published only if it carries the `dev` label — add it to the PR to get a `dev` release; otherwise the release is skipped.
82
+ > Pull requests coming from forks always run in dry-run mode: nothing is published, and no changelog link is resolved.
83
+
84
+ ### 2. Push to `develop`
85
+
86
+ - Impacted packages are published as: `x.y.z-rc.<timestamp>`
87
+ - npm dist-tag: `rc`
88
+
89
+ ### 3. Push to `main`
90
+
91
+ - Stable publication: `x.y.z`
92
+ - npm dist-tag: `latest`
93
+ - The pending changesets are consumed: the repository version is bumped, the `CHANGELOG.md` is updated, the consumed changesets are removed, and the result is committed and pushed back to `main` as `github-actions[bot]`.
94
+
95
+ ### Graph
96
+
97
+ ```mermaid
98
+ flowchart LR
99
+ EVENT("WORKFLOW TRIGGER")
100
+ HAS_DEV_TAG{"has &quot;dev&quot; label?"}
101
+ SKIP_BUILD(["skip build"])
102
+ BUILD_DEV_PACKAGES["build &quot;dev&quot; packages"]
103
+ PUBLISH_DEV_PACKAGES["publish &quot;dev&quot; packages"]
104
+ BUILD_RC_PACKAGES["build &quot;rc&quot; packages"]
105
+ PUBLISH_RC_PACKAGES["publish &quot;rc&quot; packages"]
106
+ BUILD_PROD_PACKAGES["build &quot;prod&quot; packages"]
107
+ PUBLISH_PROD_PACKAGES["publish &quot;prod&quot; packages"]
108
+ COMMIT_VERSION_BUMP["commit &amp; push the version bump"]
109
+ TARGET_BRANCH{"branch"}
110
+
111
+ EVENT -- "pull_request" --> HAS_DEV_TAG
112
+ HAS_DEV_TAG -- "no" --> SKIP_BUILD
113
+ HAS_DEV_TAG -- "yes" --> BUILD_DEV_PACKAGES
114
+ BUILD_DEV_PACKAGES --> PUBLISH_DEV_PACKAGES
115
+
116
+ EVENT -- "push" --> TARGET_BRANCH
117
+
118
+ TARGET_BRANCH -- "develop" --> BUILD_RC_PACKAGES
119
+ BUILD_RC_PACKAGES --> PUBLISH_RC_PACKAGES
120
+
121
+ TARGET_BRANCH -- "main" --> BUILD_PROD_PACKAGES
122
+ BUILD_PROD_PACKAGES --> PUBLISH_PROD_PACKAGES
123
+ PUBLISH_PROD_PACKAGES --> COMMIT_VERSION_BUMP
124
+ ```
125
+
126
+ ## Important Rules
127
+
128
+ - If an equivalent **stable** version already exists on npm: CI `push` releases skip the publication with a warning (nothing to release), while manual releases and `dev` pull requests fail — add a changeset to bump the version automatically (manual `package.json#version` bumps are no longer needed).
129
+ - The `package.json` version in the repo must always be a stable version (`x.y.z`): the version bumps come from the changesets, consumed on `main` only.
130
+ - The `-dev` / `-rc` suffixes are generated in CI.
131
+ - The npm publish authenticates with [GitHub Actions OIDC](https://docs.github.com/en/actions/security-for-github-actions/security-hardening-your-deployments/about-security-hardening-with-oidc): no `NPM_TOKEN` secret is required (the `release.yml` workflow requests the `id-token: write` permission).
package/README.md CHANGED
@@ -2,6 +2,7 @@
2
2
  ![npm](https://img.shields.io/npm/dm/@thingmate/zekta-time-series.svg)
3
3
  ![NPM](https://img.shields.io/npm/l/@thingmate/zekta-time-series.svg)
4
4
  ![npm type definitions](https://img.shields.io/npm/types/@thingmate/zekta-time-series.svg)
5
+ ![AI generation](https://img.shields.io/badge/AI_generation-medium-yellow)
5
6
 
6
7
  <picture>
7
8
  <source height="64" media="(prefers-color-scheme: dark)" srcset="https://github.com/thingmate/website/blob/main/assets/logo/png/logo-large-dark.png?raw=true">
@@ -11,7 +12,7 @@
11
12
 
12
13
  ## @thingmate/zekta-time-series
13
14
 
14
- Zekta time series implementation
15
+ File-system backed time series: fixed-length values stored in time-bucketed files, with bytes, number and text specializations.
15
16
 
16
17
  ## 📦 Installation
17
18
 
@@ -21,6 +22,233 @@ yarn add @thingmate/zekta-time-series
21
22
  npm install @thingmate/zekta-time-series --save
22
23
  ```
23
24
 
25
+ > [!NOTE]
26
+ > Requires Node.js >= 24
27
+
24
28
  ## 📜 Documentation
25
29
 
26
- TODO
30
+ This library implements the abstract `TimeSeries` class from
31
+ [`@thingmate/time-series`](https://www.npmjs.com/package/@thingmate/time-series) on top of the
32
+ Node.js file system: values associated with Unix timestamps (in seconds), persisted in a directory
33
+ of your choice. Entries are always kept sorted by time, and every time range accepted by `select`
34
+ and `delete` is inclusive on both ends.
35
+
36
+ It ships four classes, sharing the same operations (`push`, `insert`, `select`, `delete`, `drop`,
37
+ `flush`) and the same open-time options:
38
+
39
+ | Class | Value type | Storage |
40
+ | ----------------------- | --------------------------- | ------------------------------------------------- |
41
+ | `ZektaTimeSeries` | `Uint8Array` (fixed length) | time-bucketed binary files |
42
+ | `ZektaBytesTimeSeries` | `Uint8Array` (any length) | content-addressed files, deduplicated by sha256 |
43
+ | `ZektaNumberTimeSeries` | `number` | fixed-length little-endian numbers (`u8` … `f64`) |
44
+ | `ZektaTextTimeSeries` | `string` | UTF-8 stored through `ZektaBytesTimeSeries` |
45
+
46
+ ### ZektaTimeSeries
47
+
48
+ A time series of fixed-length byte-array values (`valueByteLength`), split across bucket files: each
49
+ bucket covers a fixed time range (`bucketTimeRange`, in seconds) and holds all its entries sorted by
50
+ time.
51
+
52
+ ```ts
53
+ declare class ZektaTimeSeries extends TimeSeries<Uint8Array> {
54
+ static open(options: OpenZektaTimeSeriesOptions): Promise<ZektaTimeSeries>;
55
+
56
+ push(time: number, value: Uint8Array): Promise<void>;
57
+ insert(entries: readonly TimeSeriesEntry<Uint8Array>[]): Promise<void>;
58
+ select(options?: TimeSeriesSelectOptions): Promise<readonly TimeSeriesEntry<Uint8Array>[]>;
59
+ delete(options?: TimeSeriesDeleteOptions): Promise<void>;
60
+ drop(): Promise<void>;
61
+ flush(options?: { unload?: boolean }): Promise<void>;
62
+ }
63
+ ```
64
+
65
+ **Example:** write and read entries
66
+
67
+ ```ts
68
+ import { ZektaTimeSeries } from '@thingmate/zekta-time-series';
69
+
70
+ const timeSeries: ZektaTimeSeries = await ZektaTimeSeries.open({
71
+ dirPath: './sensor-data',
72
+ valueByteLength: 4, // every value is exactly 4 bytes
73
+ });
74
+
75
+ await timeSeries.push(1700000000, new Uint8Array([21, 0, 0, 0])); // 2023-11-14T22:13:20Z
76
+ await timeSeries.insert([
77
+ { time: 1700000060, value: new Uint8Array([22, 0, 0, 0]) },
78
+ { time: 1700000120, value: new Uint8Array([23, 0, 0, 0]) },
79
+ ]);
80
+
81
+ await timeSeries.select(); // every entry, sorted by time (ascending)
82
+ await timeSeries.select({ from: 1700000000, asc: false }); // newest entries first
83
+ await timeSeries.select({ from: 1700000000, to: 1700000060 }); // both bounds are included
84
+
85
+ await timeSeries.delete({ from: 1700000000, to: 1700000060 });
86
+ await timeSeries.drop(); // removes every entry, the series stays usable
87
+
88
+ await timeSeries.flush({ unload: true }); // persists and releases every resource
89
+ ```
90
+
91
+ `select` and `delete` accept a partial time range (`from`, `to`) and, for `select`, an `asc` order
92
+ flag; missing bounds are unbounded, so an empty call covers every entry.
93
+
94
+ > [!NOTE]
95
+ > The shared `TimeSeries` operations and options are documented in
96
+ > [`@thingmate/time-series`](https://www.npmjs.com/package/@thingmate/time-series).
97
+
98
+ #### Open options
99
+
100
+ | Option | Default when creating | Description |
101
+ | ----------------- | --------------------- | ------------------------------------------------------------------------------------------------------------- |
102
+ | `dirPath` | — (required) | Directory holding the series: `zekta.config.json` and the `buckets/` sub-directory. Created with the series. |
103
+ | `valueByteLength` | required | Byte length of every stored value. Persisted in the configuration file: re-opening with another value throws. |
104
+ | `bucketTimeRange` | `512` | Width, in seconds, of each bucket file. Persisted in the configuration file too. |
105
+ | `create` | `true` | Creates the series when the configuration file is missing. When `false`, opening a missing series throws. |
106
+
107
+ ### ZektaBytesTimeSeries
108
+
109
+ A time series of byte-array values of any length. Each value is stored once, in a file named after
110
+ its sha256 hash, and the series only references it: identical values share the same storage.
111
+
112
+ `delete` leaves the storage of removed values in place (it may be shared with the remaining
113
+ entries), while `drop` removes it entirely.
114
+
115
+ > [!TIP]
116
+ > `compact()` removes the files no longer referenced by any entry, reclaiming the storage of
117
+ > deleted values. It reads every entry of the series: call it after deletions, when you want to
118
+ > reclaim their storage.
119
+
120
+ ```ts
121
+ import { ZektaBytesTimeSeries } from '@thingmate/zekta-time-series';
122
+
123
+ const timeSeries: ZektaBytesTimeSeries = await ZektaBytesTimeSeries.open({
124
+ dirPath: './snapshots',
125
+ });
126
+
127
+ await timeSeries.push(1700000000, new Uint8Array([1, 2, 3]));
128
+
129
+ await timeSeries.delete({ from: 1700000000 });
130
+ await timeSeries.compact(); // the value is unreferenced: its file is removed
131
+ ```
132
+
133
+ ### ZektaNumberTimeSeries
134
+
135
+ A time series of numbers, stored with the fixed byte length of the given `type`.
136
+
137
+ > [!WARNING]
138
+ > Values are never validated: each type stores whatever it is given, with the underlying
139
+ > `DataView` setter semantics (`u8` … `i32` take values modulo the type range, `f16`/`f32` round
140
+ > to the type precision, `f64` stores every JavaScript number losslessly). Passing values that
141
+ > fit the type is the caller's responsibility.
142
+ >
143
+ > The `type` is not persisted with the series: re-opening with a different type of the same byte
144
+ > length (`u8` as `i8`, `u16` as `i16`, `f32` as `i32`, …) succeeds and silently reinterprets the
145
+ > stored values (a `u8` 255 reads back -1 as `i8`) — always re-open with the original type.
146
+
147
+ ```ts
148
+ import { ZektaNumberTimeSeries } from '@thingmate/zekta-time-series';
149
+
150
+ const temperatures: ZektaNumberTimeSeries = await ZektaNumberTimeSeries.open({
151
+ dirPath: './temperatures',
152
+ type: 'f32', // every number is stored on 4 bytes
153
+ });
154
+
155
+ await temperatures.push(1700000000, 21.5);
156
+
157
+ await temperatures.select(); // [{ time: 1700000000, value: 21.5 }]
158
+ ```
159
+
160
+ ### ZektaTextTimeSeries
161
+
162
+ A time series of text values, stored as UTF-8 through the content-addressed
163
+ `ZektaBytesTimeSeries`. Any well-formed string round-trips losslessly.
164
+
165
+ > [!WARNING]
166
+ > Strings containing lone surrogates are silently stored with U+FFFD replacement characters in
167
+ > their place (`TextEncoder` semantics): passing well-formed strings is the caller's
168
+ > responsibility.
169
+
170
+ ```ts
171
+ import { ZektaTextTimeSeries } from '@thingmate/zekta-time-series';
172
+
173
+ const logs: ZektaTextTimeSeries = await ZektaTextTimeSeries.open({
174
+ dirPath: './logs',
175
+ });
176
+
177
+ await logs.push(1700000000, 'system started');
178
+
179
+ await logs.select(); // [{ time: 1700000000, value: 'system started' }]
180
+ ```
181
+
182
+ ### On-disk layout
183
+
184
+ ```text
185
+ <dirPath>/
186
+ ├── zekta.config.json # { version: 1, valueByteLength, bucketTimeRange }
187
+ ├── buckets/
188
+ │ ├── 0.bucket # entries with times in [0, 512[
189
+ │ ├── 512.bucket # entries with times in [512, 1024[
190
+ │ └── ...
191
+ └── files/ # only for bytes and text series
192
+ └── 9f86d081884c7d65... # one file per stored value, named after its sha256 hash
193
+ ```
194
+
195
+ Each bucket file is a sequence of entries kept sorted by time: every entry is its time (8-byte
196
+ little-endian float64) followed by its value (`valueByteLength` bytes).
197
+
198
+ ### Persistence and crash safety
199
+
200
+ Writes are applied in memory first and persisted to disk automatically (~1s after the first pending
201
+ change), or immediately through `flush()`. Buckets left idle for ~5s release their in-memory copy:
202
+ the next operation reloads it from disk.
203
+
204
+ > [!TIP]
205
+ > `TimeSeries` implements `AsyncDisposable`: `await using` flushes the pending changes when
206
+ > leaving the scope.
207
+
208
+ ```ts
209
+ {
210
+ await using timeSeries: ZektaTextTimeSeries = await ZektaTextTimeSeries.open({
211
+ dirPath: './logs',
212
+ });
213
+
214
+ await timeSeries.push(1700000000, 'system started');
215
+ // `flush` is called when leaving this scope
216
+ }
217
+ ```
218
+
219
+ Bucket files are written atomically (temp file + rename) whenever their content changes mid-file;
220
+ pure appends and truncations are done in place, and a torn tail left by an interrupted append is
221
+ repaired (trimmed) on the next load. A failed persistence never loses the in-memory data: the next
222
+ flush retries. Leftover temp files from interrupted flushes are cleaned up when the series is
223
+ opened.
224
+
225
+ ### Validation contract
226
+
227
+ - `push` and `insert` reject non-finite times (`RangeError`) and values whose length differs from
228
+ `valueByteLength` (`Error`).
229
+ - `insert` is atomic: every entry is validated first, so a failing batch leaves the series
230
+ untouched.
231
+ - Times are Unix timestamps in seconds; `select` and `delete` time ranges are inclusive on both
232
+ ends.
233
+
234
+ ### Benchmarks
235
+
236
+ The repository ships a benchmark (`src/zekta-time-series.bench.ts`) comparing `ZektaTimeSeries`
237
+ with `node:sqlite` on the three typical time-series workloads. The setup is kept symmetric: both
238
+ sides persist to a real file and pay their storage creation and write durability point inside the
239
+ measured section (`flush()` versus `COMMIT`), and `node:sqlite` runs with its standard
240
+ fast-durable configuration (`journal_mode = WAL`, `synchronous = NORMAL`, prepared statements,
241
+ every insert grouped in a single transaction — its best realistic bulk-write configuration). Each
242
+ measured operation handles 1000 entries of 16 bytes.
243
+
244
+ Mean time per operation, averaged over three runs (lower is better), Node.js v26 on an Intel
245
+ Core i7-8750H:
246
+
247
+ | Workload | ZektaTimeSeries | node:sqlite | Ratio |
248
+ | ------------------------------------------- | --------------- | ----------- | ----- |
249
+ | Ingestion: 1000 sequential `push` + `flush` | ~6.5 ms | ~16 ms | ~2.4× |
250
+ | Backfill: one 1000-entry `insert` + `flush` | ~6.2 ms | ~15 ms | ~2.4× |
251
+ | Range read: `select` of 1000 entries | ~0.12 ms | ~0.97 ms | ~7.8× |
252
+
253
+ Benchmarks are indicative and machine-dependent: re-run them with `yarn fb:bench
254
+ --reporter=verbose`.
package/package.json CHANGED
@@ -1,56 +1,42 @@
1
1
  {
2
2
  "name": "@thingmate/zekta-time-series",
3
- "version": "0.1.0",
3
+ "version": "1.0.0",
4
4
  "type": "module",
5
- "main": "./index.js",
6
- "scripts": {
7
- "fb:build": "node fabrique/actions/cli/build.cli.js",
8
- "fb:format": "prettier --write --ignore-unknown --config ./.prettierrc \"src/**/*.{js,jsx,ts,tsx,html,css,scss}\"",
9
- "fb:test": "vitest",
10
- "fb:test:coverage": "vitest run --coverage",
11
- "fb:bench": "vitest bench",
12
- "fb:typedoc": "typedoc --options typedoc.json --tsconfig tsconfig.json",
13
- "fb:prod": "node fabrique/actions/cli/build-and-publish.cli.js --mode prod",
14
- "fb:dev": "node fabrique/actions/cli/build-and-publish.cli.js --mode dev",
15
- "fb:rc": "node fabrique/actions/cli/build-and-publish.cli.js --mode rc",
16
- "fb:node:dev": "node --experimental-strip-types --watch src/main.ts",
17
- "fb:node:dev:inspect": "node --experimental-strip-types --watch --inspect src/main.ts"
18
- },
19
- "description": "Zekta time series implementation",
20
- "keywords": [],
5
+ "description": "File-system backed time series: fixed-length values stored in time-bucketed files, with bytes, number and text specializations.",
6
+ "keywords": [
7
+ "time-series",
8
+ "timeseries",
9
+ "storage",
10
+ "persistence",
11
+ "filesystem",
12
+ "database",
13
+ "embedded",
14
+ "buckets",
15
+ "sensor-data",
16
+ "metrics"
17
+ ],
21
18
  "author": "Valentin Richard",
22
19
  "license": "MIT",
23
- "access": "public",
24
20
  "repository": {
25
21
  "type": "git",
26
22
  "url": "git+https://github.com/thingmate/zekta-time-series.git"
27
23
  },
28
- "devDependencies": {
29
- "@types/node": "^25.0.7",
30
- "@vitest/coverage-istanbul": "^4.0.17",
31
- "prettier": "^3.7.4",
32
- "prettier-plugin-organize-imports": "^4.3.0",
33
- "typedoc": "^0.28.16",
34
- "typescript": "^5.9.3",
35
- "vitest": "^4.0.17"
36
- },
37
- "packageManager": "yarn@4.12.0",
38
- "fabrique": {
39
- "version": "1.1.1",
40
- "type": "lib"
24
+ "main": "./src/index.js",
25
+ "types": "./src/index.d.ts",
26
+ "exports": {
27
+ ".": {
28
+ "types": "./src/index.d.ts",
29
+ "default": "./src/index.js"
30
+ }
41
31
  },
42
32
  "dependencies": {
43
- "@thingmate/time-series": "^0.1.1",
33
+ "@thingmate/time-series": "^1.0.0",
44
34
  "@xstd/hex": "^0.1.0",
45
35
  "@xstd/path": "^1.0.0",
46
- "@xstd/sha256": "^1.0.0"
47
- },
48
- "exports": {
49
- ".": {
50
- "types": "./index.d.ts",
51
- "default": "./index.js"
52
- }
36
+ "@xstd/sha256": "^1.0.0",
37
+ "zod": "^4.6.7"
53
38
  },
54
- "typings": "./index.d.ts",
55
- "types": "./index.d.ts"
39
+ "engines": {
40
+ "node": ">=24.0.0"
41
+ }
56
42
  }
@@ -0,0 +1,15 @@
1
+ import { type PathInput } from '@xstd/path';
2
+ /**
3
+ * Deletes the temp files left behind in the given directory by flushes which
4
+ * were interrupted (crashed process in the middle of a write). Best placed
5
+ * on the directory which contains the buckets directory: it is where flushes
6
+ * write their temp files. A missing directory is a no-op.
7
+ */
8
+ export declare function cleanupBucketTempFiles(directoryPath: PathInput): Promise<void>;
9
+ /**
10
+ * Returns a unique temporary file name (".zekta-bucket-&lt;uuid&gt;.tmp").
11
+ *
12
+ * Leftover temp files from interrupted writes are removed by
13
+ * {@link cleanupBucketTempFiles}.
14
+ */
15
+ export declare function createBucketTempFileName(): string;
@@ -0,0 +1,47 @@
1
+ import { Path } from '@xstd/path';
2
+ import { randomUUID } from 'node:crypto';
3
+ import { readdir, rm } from 'node:fs/promises';
4
+ const BUCKET_TEMP_FILE_NAME_PREFIX = '.zekta-bucket-';
5
+ const BUCKET_TEMP_FILE_NAME_SUFFIX = '.tmp';
6
+ /**
7
+ * Deletes the temp files left behind in the given directory by flushes which
8
+ * were interrupted (crashed process in the middle of a write). Best placed
9
+ * on the directory which contains the buckets directory: it is where flushes
10
+ * write their temp files. A missing directory is a no-op.
11
+ */
12
+ export async function cleanupBucketTempFiles(directoryPath) {
13
+ const directory = Path.of(directoryPath);
14
+ let tempFilePaths;
15
+ try {
16
+ tempFilePaths = (await readdir(directory.toString(), { withFileTypes: true }))
17
+ .filter((entry) => {
18
+ return (entry.isFile() &&
19
+ entry.name.startsWith(BUCKET_TEMP_FILE_NAME_PREFIX) &&
20
+ entry.name.endsWith(BUCKET_TEMP_FILE_NAME_SUFFIX) &&
21
+ entry.name.length >
22
+ BUCKET_TEMP_FILE_NAME_PREFIX.length + BUCKET_TEMP_FILE_NAME_SUFFIX.length);
23
+ })
24
+ .map((entry) => {
25
+ return directory.concat(entry.name);
26
+ });
27
+ }
28
+ catch (error) {
29
+ if (error.code === 'ENOENT') {
30
+ return; /* nothing to clean up */
31
+ }
32
+ throw error;
33
+ }
34
+ await Promise.all(tempFilePaths.map((filePath) => {
35
+ return rm(filePath.toString(), { force: true });
36
+ }));
37
+ }
38
+ /**
39
+ * Returns a unique temporary file name (".zekta-bucket-&lt;uuid&gt;.tmp").
40
+ *
41
+ * Leftover temp files from interrupted writes are removed by
42
+ * {@link cleanupBucketTempFiles}.
43
+ */
44
+ export function createBucketTempFileName() {
45
+ return `${BUCKET_TEMP_FILE_NAME_PREFIX}${randomUUID()}${BUCKET_TEMP_FILE_NAME_SUFFIX}`;
46
+ }
47
+ //# sourceMappingURL=temp-files.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"temp-files.js","sourceRoot":"","sources":["../../../../../src/bucket.private/helpers.private/temp-files/temp-files.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAkB,MAAM,YAAY,CAAC;AAClD,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAEzC,OAAO,EAAE,OAAO,EAAE,EAAE,EAAE,MAAM,kBAAkB,CAAC;AAE/C,MAAM,4BAA4B,GAAW,gBAAgB,CAAC;AAC9D,MAAM,4BAA4B,GAAW,MAAM,CAAC;AAEpD;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,sBAAsB,CAAC,aAAwB;IACnE,MAAM,SAAS,GAAS,IAAI,CAAC,EAAE,CAAC,aAAa,CAAC,CAAC;IAC/C,IAAI,aAAqB,CAAC;IAC1B,IAAI,CAAC;QACH,aAAa,GAAG,CAAC,MAAM,OAAO,CAAC,SAAS,CAAC,QAAQ,EAAE,EAAE,EAAE,aAAa,EAAE,IAAI,EAAE,CAAC,CAAC;aAC3E,MAAM,CAAC,CAAC,KAAK,EAAW,EAAE;YACzB,OAAO,CACL,KAAK,CAAC,MAAM,EAAE;gBACd,KAAK,CAAC,IAAI,CAAC,UAAU,CAAC,4BAA4B,CAAC;gBACnD,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC,4BAA4B,CAAC;gBACjD,KAAK,CAAC,IAAI,CAAC,MAAM;oBACf,4BAA4B,CAAC,MAAM,GAAG,4BAA4B,CAAC,MAAM,CAC5E,CAAC;QACJ,CAAC,CAAC;aACD,GAAG,CAAC,CAAC,KAAa,EAAQ,EAAE;YAC3B,OAAO,SAAS,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;QACtC,CAAC,CAAC,CAAC;IACP,CAAC;IAAC,OAAO,KAAc,EAAE,CAAC;QACxB,IAAK,KAA2B,CAAC,IAAI,KAAK,QAAQ,EAAE,CAAC;YACnD,OAAO,CAAC,yBAAyB;QACnC,CAAC;QACD,MAAM,KAAK,CAAC;IACd,CAAC;IAED,MAAM,OAAO,CAAC,GAAG,CACf,aAAa,CAAC,GAAG,CAAC,CAAC,QAAc,EAAiB,EAAE;QAClD,OAAO,EAAE,CAAC,QAAQ,CAAC,QAAQ,EAAE,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;IAClD,CAAC,CAAC,CACH,CAAC;AACJ,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,wBAAwB;IACtC,OAAO,GAAG,4BAA4B,GAAG,UAAU,EAAE,GAAG,4BAA4B,EAAE,CAAC;AACzF,CAAC"}