Skip to content

Commit

Permalink
feat(parse): accept gzip-encoded values for VehiclePositions
Browse files Browse the repository at this point in the history
  • Loading branch information
paulswartz committed Sep 18, 2023
1 parent b714ba5 commit 9a9935c
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 9 deletions.
24 changes: 19 additions & 5 deletions apps/parse/lib/parse/vehicle_positions.ex
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,30 @@ defmodule Parse.VehiclePositions do
alias Parse.Realtime.FeedMessage
import Parse.Helpers

def parse(<<31, 139, _::binary>> = blob) do
# gzip encoded
blob
|> :zlib.gunzip()
|> parse
end

def parse("{" <> _ = blob) do
Parse.VehiclePositionsJson.parse(blob)
end

def parse(blob) do
blob
|> FeedMessage.decode()
|> (fn message -> message.entity end).()
|> Stream.map(fn entity -> entity.vehicle end)
|> Stream.map(&parse_vehicle_update/1)
decoded = FeedMessage.decode(blob)

entities =
decoded.entity
|> Stream.map(fn entity -> entity.vehicle end)
|> Stream.map(&parse_vehicle_update/1)

if decoded.header.incrementality == :DIFFERENTIAL do
{:partial, entities}
else
entities
end
end

def parse_vehicle_update(update) do
Expand Down
20 changes: 16 additions & 4 deletions apps/parse/lib/parse/vehicle_positions_json.ex
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,18 @@ defmodule Parse.VehiclePositionsJson do
alias Model.Vehicle

def parse(body) do
body
|> Jason.decode!(strings: :copy)
|> Map.get("entity")
|> Enum.flat_map(&parse_entity/1)
decoded = Jason.decode!(body, strings: :copy)

entities =
decoded
|> Map.get("entity")
|> Enum.flat_map(&parse_entity/1)

if decoded["header"]["incrementality"] in ["DIFFERENTIAL", 1] do
{:partial, entities}
else
entities
end
end

def parse_entity(
Expand Down Expand Up @@ -109,6 +117,10 @@ defmodule Parse.VehiclePositionsJson do
Parse.Timezone.unix_to_local(timestamp)
end

defp unix_to_local(timestamp) when is_float(timestamp) do
Parse.Timezone.unix_to_local(trunc(timestamp))
end

defp unix_to_local(nil) do
DateTime.utc_now()
end
Expand Down
6 changes: 6 additions & 0 deletions apps/parse/test/parse/vehicle_positions_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,12 @@ defmodule Parse.VehiclePositionsTest do
actual = parse(body)
assert actual == expected
end

test "can parse gzip-encoded JSON" do
body = :zlib.gzip(Jason.encode!(%{entity: [@vehicle]}))
actual = parse(body)
assert [_] = actual
end
end

describe "parse_vehicle_update/1" do
Expand Down

0 comments on commit 9a9935c

Please sign in to comment.